Exception example



  /** * Adds a blank section to the list. * * @return $this * * @see \Drupal\layout_builder\Plugin\Layout\BlankLayout */
  protected function addBlankSection() {
    if ($this->hasSection(0)) {
      throw new \Exception('A blank section must only be added to an empty list');
    }

    $this->appendSection(new Section('layout_builder_blank'));
    return $this;
  }

  /** * Indicates if this section list contains a blank section. * * A blank section is used to differentiate the difference between a layout * that has never been instantiated and one that has purposefully had all * sections removed. * * @return bool * TRUE if the section list contains a blank section, FALSE otherwise. * * @see \Drupal\layout_builder\Plugin\Layout\BlankLayout */

function _wp_json_sanity_check( $data$depth ) {
    if ( $depth < 0 ) {
        throw new Exception( 'Reached depth limit' );
    }

    if ( is_array( $data ) ) {
        $output = array();
        foreach ( $data as $id => $el ) {
            // Don't forget to sanitize the ID!             if ( is_string( $id ) ) {
                $clean_id = _wp_json_convert_string( $id );
            } else {
                $clean_id = $id;
            }

            
'message' => 'Llamas are awesome!',
    ]);
    $message->save();

    return $message;
  }

  /** * {@inheritdoc} */
  protected function getExpectedDocument() {
    throw new \Exception('Not yet supported.');
  }

  /** * {@inheritdoc} */
  protected function getPostDocument() {
    return [
      'data' => [
        'type' => 'contact_message--camelids',
        'attributes' => [
          'subject' => 'Dramallama',
          
public function handle(Request $request$type = self::MAIN_REQUEST, $catch = TRUE): Response {
    if (\Drupal::state()->get('error_service_test.break_bare_html_renderer')) {
      // Let the bedlam begin.       // 1) Force a container rebuild.       /** @var \Drupal\Core\DrupalKernelInterface $kernel */
      $kernel = \Drupal::service('kernel');
      $kernel->rebuildContainer();
      // 2) Fetch the in-situ container builder.       $container = ErrorServiceTestServiceProvider::$containerBuilder;
      // Ensure the compiler pass worked.       if (!$container) {
        throw new \Exception('Oh oh, monkeys stole the ServiceProvider.');
      }
      // Stop the theme manager from being found - and triggering error       // maintenance mode.       $container->removeDefinition('theme.manager');
      // Mash. Mash. Mash.       \Drupal::setContainer($container);
      throw new \Exception('Oh oh, bananas in the instruments.');
    }

    if (\Drupal::state()->get('error_service_test.break_logger')) {
      throw new \Exception('Deforestation');
    }
$this->assertResponseFromException($request$exception$response);
    $this->assertTrue($this->event->isAllowingCustomResponseCode());
    $this->assertSame(200, $this->event->getResponse()->getStatusCode());
  }

  /** * @covers ::onException */
  public function testOnExceptionOtherClass() {
    $request = new Request();
    $exception = new \Exception();

    $this->formAjaxResponseBuilder->expects($this->never())
      ->method('buildResponse');

    $this->assertResponseFromException($request$exception, NULL);
  }

  /** * @covers ::onException */
  public function testOnExceptionResponseBuilderException() {
    
$this->assertNotNull($sentToFailureTransportStamp);
            $this->assertSame($receiverName$sentToFailureTransportStamp->getOriginalReceiverName());

            return true;
        }))->willReturnArgument(0);

        $serviceLocator = $this->createMock(ServiceLocator::class);
        $serviceLocator->expects($this->once())->method('has')->willReturn(true);
        $serviceLocator->expects($this->once())->method('get')->with($receiverName)->willReturn($sender);
        $listener = new SendFailedMessageToFailureTransportListener($serviceLocator);

        $exception = new \Exception('no!');
        $envelope = new Envelope(new \stdClass());
        $event = new WorkerMessageFailedEvent($envelope, 'my_receiver', $exception);

        $listener->onMessageFailed($event);
    }

    public function testDoNothingOnRetryWithServiceLocator()
    {
        $sender = $this->createMock(SenderInterface::class);
        $sender->expects($this->never())->method('send');

        
$this->expectExceptionMessage(sprintf('File "%s" does not contain valid XML, it is empty.', $file));

        XmlUtils::loadFile($file);
    }

    // test for issue https://github.com/symfony/symfony/issues/9731     public function testLoadWrongEmptyXMLWithErrorHandler()
    {
        $errorReporting = error_reporting(-1);

        set_error_handler(function D$errno$errstr) {
            throw new \Exception($errstr$errno);
        });

        $file = __DIR__.'/../Fixtures/foo.xml';
        try {
            try {
                XmlUtils::loadFile($file);
                $this->fail('An exception should have been raised');
            } catch (\InvalidArgumentException $e) {
                $this->assertEquals(sprintf('File "%s" does not contain valid XML, it is empty.', $file)$e->getMessage());
            }
        } finally {
            
$second = new class() extends HandleMessageMiddlewareTestCallable {
            public function __invoke()
            {
                return null;
            }
        };
        $secondClass = $second::class;

        $failing = new class() extends HandleMessageMiddlewareTestCallable {
            public function __invoke()
            {
                throw new \Exception('handler failed.');
            }
        };

        yield 'A stamp is added' => [
            [$first],
            [new HandledStamp('first result', $firstClass.'::__invoke')],
            true,
        ];

        yield 'A stamp is added per handler' => [
            [
                

        return new Response($this->container->get('twig')->render('@CsrfFormLogin/Login/after_login.html.twig'));
    }

    public function loginCheckAction()
    {
        return new Response('', 400);
    }

    public function secureAction()
    {
        throw new \Exception('Wrapper', 0, new \Exception('Another Wrapper', 0, new AccessDeniedException()));
    }

    public static function getSubscribedServices(): array
    {
        return [
            'form.factory' => FormFactoryInterface::class,
            'twig' => Environment::class,
        ];
    }
}
use Symfony\Component\Routing\RequestContext;

/** * Implements a URL generator which always thrown an exception. */
class SupernovaGenerator implements UrlGeneratorInterface {

  /** * {@inheritdoc} */
  public function setContext(RequestContext $context) {
    throw new \Exception();
  }

  /** * {@inheritdoc} */
  public function getContext(): RequestContext {
    throw new \Exception();
  }

  /** * {@inheritdoc} */
if (null !== $env) {
            parent::__construct($env);
        }
        $this->parent = false;
        $this->blocks = [];
        $this->path = $path;
    }

    protected function doDisplay(array $context, array $blocks = [])
    {
        // line 2         throw new \Exception('Foobar');
    }

    public function getTemplateName()
    {
        return 'foo.twig';
    }

    public function getDebugInfo()
    {
        return [33 => 1, 34 => 2];
    }

    

  public function getDataDefinition() {
    if ($this->isMultiple()) {
      $definition = $this->getTypedDataManager()->createListDataDefinition($this->getDataType());
    }
    else {
      $definition = $this->getTypedDataManager()->createDataDefinition($this->getDataType());
    }

    if (!$definition) {
      throw new \Exception("The data type '{$this->getDataType()}' is invalid");
    }
    $definition->setLabel($this->getLabel())
      ->setDescription($this->getDescription())
      ->setRequired($this->isRequired());
    $constraints = $definition->getConstraints() + $this->getConstraints();
    $definition->setConstraints($constraints);
    return $definition;
  }

  /** * Checks if this definition's data type matches that of the given context. * * @param \Drupal\Core\Plugin\Context\ContextInterface $context * The context to test against. * * @return bool * TRUE if the data types match, otherwise FALSE. */
$output[] = array( 'op', array_pop( $stack ) );
                                continue;
                            }

                            // Discard open paren.                             array_pop( $stack );
                            $found = true;
                            break;
                        }

                        if ( ! $found ) {
                            throw new Exception( 'Mismatched parentheses' );
                        }

                        $pos++;
                        break;

                    // Operators.                     case '|':
                    case '&':
                    case '>':
                    case '<':
                    case '!':
                    


    $function("test-string");
    return [];
  }

  /** * Trigger an exception to test the exception handler. */
  public function triggerException() {
    define('SIMPLETEST_COLLECT_ERRORS', FALSE);
    throw new \Exception("Drupal & awesome");
  }

  /** * Trigger an exception to test the PDO exception handler. */
  public function triggerPDOException() {
    define('SIMPLETEST_COLLECT_ERRORS', FALSE);
    $this->database->select('bananas_are_awesome', 'b')
      ->fields('b')
      ->execute();
  }

  
$exception = new MissingMandatoryParametersException('expected legacy message');
        $this->assertSame('expected legacy message', $exception->getMessage());
    }

    /** * @group legacy */
    public function testLegacyThrowingMissingMandatoryParametersWithAllParameters()
    {
        $this->expectDeprecation('Since symfony/routing 6.1: Construction of "Symfony\Component\Routing\Exception\MissingMandatoryParametersException" with an exception message is deprecated, provide the route name and an array of missing parameters instead.');

        $exception = new MissingMandatoryParametersException('expected legacy message', 256, new \Exception());
        $this->assertSame('expected legacy message', $exception->getMessage());
        $this->assertInstanceOf(\Exception::class$exception->getPrevious());
    }

    public function testGenerateForRouteWithoutMandatoryParameter()
    {
        $this->expectException(MissingMandatoryParametersException::class);
        $this->expectExceptionMessage('Some mandatory parameters are missing ("foo") to generate a URL for route "test".');
        $routes = $this->getRoutes('test', new Route('/testing/{foo}'));
        $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_URL);
    }

    
Home | Imprint | This part of the site doesn't use cookies.