ExceptionEvent example

$requestStack = new RequestStack();
        $requestStack->push($mainRequest);

        $onlyException = true;
        $listener = new ProfilerListener($profiler$requestStack, null, $onlyException);

        // main request         $listener->onKernelResponse(new ResponseEvent($kernel$mainRequest, Kernel::MAIN_REQUEST, $response));

        // sub request         $listener->onKernelException(new ExceptionEvent($kernel$subRequest, Kernel::SUB_REQUEST, new HttpException(404)));
        $listener->onKernelResponse(new ResponseEvent($kernel$subRequest, Kernel::SUB_REQUEST, $response));

        $listener->onKernelTerminate(new TerminateEvent($kernel$mainRequest$response));
    }

    /** * @dataProvider collectRequestProvider */
    public function testCollectParameter(Request $request, ?bool $enable)
    {
        $profile = new Profile('token');

        

    private function finishRequest(Request $request, int $type): void
    {
        $this->dispatcher->dispatch(new FinishRequestEvent($this$request$type), KernelEvents::FINISH_REQUEST);
    }

    /** * Handles a throwable by trying to convert it to a Response. */
    private function handleThrowable(\Throwable $e, Request $request, int $type): Response
    {
        $event = new ExceptionEvent($this$request$type$e);
        $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION);

        // a listener might have replaced the exception         $e = $event->getThrowable();

        if (!$event->hasResponse()) {
            $this->finishRequest($request$type);

            throw $e;
        }

        
->willReturnCallback(function D&$elements) use ($rendered_output) {
        $elements['#attached'] = [];
        return $rendered_output;
      });
    $container = new ContainerBuilder();
    $container->set('renderer', $renderer);
    \Drupal::setContainer($container);

    $exception = new BrokenPostRequestException(32 * 1e6);
    $request = new Request([FormBuilderInterface::AJAX_FORM_REQUEST => TRUE]);

    $event = new ExceptionEvent($this->httpKernel, $request, HttpKernelInterface::MAIN_REQUEST, $exception);
    $this->subscriber->onException($event);
    $this->assertTrue($event->isAllowingCustomResponseCode());
    $actual_response = $event->getResponse();
    $this->assertInstanceOf('\Drupal\Core\Ajax\AjaxResponse', $actual_response);
    $this->assertSame(200, $actual_response->getStatusCode());
    $expected_commands[] = [
      'command' => 'insert',
      'method' => 'prepend',
      'selector' => NULL,
      'data' => $rendered_output,
      'settings' => NULL,
    ];
$request_context = new RequestContext();
    $request_context->fromRequest($request);
    $this->accessUnawareRouter->expects($this->any())
      ->method('getContext')
      ->willReturn($request_context);

    $this->kernel->expects($this->once())->method('handle')->willReturnCallback(function DRequest $request) {
      return new HtmlResponse($request->getMethod());
    });

    $event = new ExceptionEvent($this->kernel, $request, HttpKernelInterface::MAIN_REQUEST, new NotFoundHttpException('foo'));

    $this->customPageSubscriber->onException($event);

    $response = $event->getResponse();
    $result = $response->getContent() . " " . UrlHelper::buildQuery($request->request->all());
    $this->assertEquals('POST name=druplicon&pass=12345', $result);
    $this->assertEquals(AccessResult::allowed()->addCacheTags(['foo', 'bar'])$request->attributes->get(AccessAwareRouterInterface::ACCESS_RESULT));
  }

  /** * Tests onHandleException with a GET request. */

        $trustResolver = $this->createMock(AuthenticationTrustResolverInterface::class);
        $trustResolver->expects($this->once())->method('isFullFledged')->willReturn($fullFledged);

        return $trustResolver;
    }

    private function createEvent(\Exception $exception$kernel = null)
    {
        $kernel ??= $this->createMock(HttpKernelInterface::class);

        return new ExceptionEvent($kernel, Request::create('/'), HttpKernelInterface::MAIN_REQUEST, $exception);
    }

    private function createExceptionListener(TokenStorageInterface $tokenStorage = null, AuthenticationTrustResolverInterface $trustResolver = null, HttpUtils $httpUtils = null, AuthenticationEntryPointInterface $authenticationEntryPoint = null, $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null)
    {
        return new ExceptionListener(
            $tokenStorage ?? $this->createMock(TokenStorageInterface::class),
            $trustResolver ?? $this->createMock(AuthenticationTrustResolverInterface::class),
            $httpUtils ?? $this->createMock(HttpUtils::class),
            'key',
            $authenticationEntryPoint,
            $errorPage,
            
        if (null !== $reference) {
            $subRequest->attributes->add($reference->attributes);
        }

        $level = ob_get_level();
        try {
            return SubRequestHandler::handle($this->kernel, $subRequest, HttpKernelInterface::SUB_REQUEST, false);
        } catch (\Exception $e) {
            // we dispatch the exception event to trigger the logging             // the response that comes back is ignored             if (isset($options['ignore_errors']) && $options['ignore_errors'] && $this->dispatcher) {
                $event = new ExceptionEvent($this->kernel, $request, HttpKernelInterface::SUB_REQUEST, $e);

                $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION);
            }

            // let's clean up the output buffers that were created by the sub-request             Response::closeOutputBuffers($level, false);

            if (isset($options['alt'])) {
                $alt = $options['alt'];
                unset($options['alt']);

                

  public function testOnExceptionWithUnknownFormat() {
    $config_factory = $this->getConfigFactoryStub();

    $kernel = $this->prophesize(HttpKernelInterface::class);
    $request = Request::create('/test');
    // \Drupal\Core\StackMiddleware\NegotiationMiddleware normally takes care     // of this so we'll hard code it here.     $request->setRequestFormat('bananas');
    $e = new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message');
    $event = new ExceptionEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST, $e);
    $subscriber = new TestDefaultExceptionSubscriber($config_factory);
    $subscriber->setStringTranslation($this->getStringTranslationStub());
    $subscriber->onException($event);
    $response = $event->getResponse();

    $this->assertInstanceOf(Response::class$response);
    $this->assertStringStartsWith('The website encountered an unexpected error. Please try again later.<br><br><em class="placeholder">Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException</em>: test message in ', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    // Also check that the text/plain content type was added.     $this->assertEquals('text/plain', $response->headers->get('Content-Type'));
  }
$strategy = new InlineFragmentRenderer($this->getKernel($this->throwException(new \RuntimeException('foo')))$dispatcher);

        $this->assertEquals('foo', $strategy->render('/', Request::create('/'))->getContent());
    }

    public function testRenderExceptionIgnoreErrors()
    {
        $exception = new \RuntimeException('foo');
        $kernel = $this->getKernel($this->throwException($exception));
        $request = Request::create('/');
        $expectedEvent = new ExceptionEvent($kernel$request$kernel::SUB_REQUEST, $exception);
        $dispatcher = $this->createMock(EventDispatcherInterface::class);
        $dispatcher->expects($this->once())->method('dispatch')->with($expectedEvent, KernelEvents::EXCEPTION);

        $strategy = new InlineFragmentRenderer($kernel$dispatcher);

        $this->assertEmpty($strategy->render('/', $request['ignore_errors' => true])->getContent());
    }

    public function testRenderExceptionIgnoreErrorsWithAlt()
    {
        $strategy = new InlineFragmentRenderer($this->getKernel($this->onConsecutiveCalls(
            
        if (null !== $reference) {
            $subRequest->attributes->add($reference->attributes);
        }

        $level = ob_get_level();
        try {
            return SubRequestHandler::handle($this->kernel, $subRequest, HttpKernelInterface::SUB_REQUEST, false);
        } catch (\Exception $e) {
            // we dispatch the exception event to trigger the logging             // the response that comes back is ignored             if (isset($options['ignore_errors']) && $options['ignore_errors'] && $this->dispatcher) {
                $event = new ExceptionEvent($this->kernel, $request, HttpKernelInterface::SUB_REQUEST, $e);

                $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION);
            }

            // let's clean up the output buffers that were created by the sub-request             Response::closeOutputBuffers($level, false);

            if (isset($options['alt'])) {
                $alt = $options['alt'];
                unset($options['alt']);

                
$this->assertEquals(3, $logger->countErrors());
        $logs = $logger->getLogs('critical');
        $this->assertCount(3, $logs);
        $this->assertStringStartsWith('Uncaught PHP Exception Exception: "foo" at ErrorListenerTest.php line', $logs[0]);
        $this->assertStringStartsWith('Uncaught PHP Exception Exception: "foo" at ErrorListenerTest.php line', $logs[1]);
        $this->assertStringStartsWith('Exception thrown when handling an exception (RuntimeException: bar at ErrorListenerTest.php line', $logs[2]);
    }

    public function testHandleWithLoggerAndCustomConfiguration()
    {
        $request = new Request();
        $event = new ExceptionEvent(new TestKernel()$request, HttpKernelInterface::MAIN_REQUEST, new \RuntimeException('bar'));
        $logger = new TestLogger();
        $l = new ErrorListener('not used', $logger, false, [
            \RuntimeException::class => [
                'log_level' => 'warning',
                'status_code' => 401,
            ],
        ]);
        $l->logKernelException($event);
        $l->onKernelException($event);

        $this->assertEquals(new Response('foo', 401)$event->getResponse());

        

class ExceptionJsonSubscriberTest extends UnitTestCase {

  /** * @covers ::on4xx * @dataProvider providerTestOn4xx */
  public function testOn4xx(HttpExceptionInterface $exception$expected_response_class) {
    $kernel = $this->prophesize(HttpKernelInterface::class);
    $request = Request::create('/test');
    $event = new ExceptionEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST, $exception);
    $subscriber = new ExceptionJsonSubscriber();
    $subscriber->on4xx($event);
    $response = $event->getResponse();

    $this->assertInstanceOf($expected_response_class$response);
    $this->assertEquals('{"message":"test message"}', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    $this->assertEquals('application/json', $response->headers->get('Content-Type'));
  }

  

    private function finishRequest(Request $request, int $type): void
    {
        $this->dispatcher->dispatch(new FinishRequestEvent($this$request$type), KernelEvents::FINISH_REQUEST);
    }

    /** * Handles a throwable by trying to convert it to a Response. */
    private function handleThrowable(\Throwable $e, Request $request, int $type): Response
    {
        $event = new ExceptionEvent($this$request$type$e);
        $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION);

        // a listener might have replaced the exception         $e = $event->getThrowable();

        if (!$event->hasResponse()) {
            $this->finishRequest($request$type);

            throw $e;
        }

        
class DefaultExceptionSubscriberTest extends UnitTestCase {

  /** * @covers ::on4xx */
  public function testOn4xx() {
    $kernel = $this->prophesize(HttpKernelInterface::class);
    $request = Request::create('/test');
    $request->setRequestFormat('json');

    $e = new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message');
    $event = new ExceptionEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST, $e);
    $subscriber = new DefaultExceptionSubscriber(new Serializer([][new JsonEncoder()])[]);
    $subscriber->on4xx($event);
    $response = $event->getResponse();

    $this->assertInstanceOf(Response::class$response);
    $this->assertEquals('{"message":"test message"}', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    $this->assertEquals('application/json', $response->headers->get('Content-Type'));
  }

}
namespace Symfony\Component\HttpKernel\Tests\Event;

use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Tests\TestHttpKernel;

class ExceptionEventTest extends TestCase
{
    public function testAllowSuccessfulResponseIsFalseByDefault()
    {
        $event = new ExceptionEvent(new TestHttpKernel()new Request(), 1, new \Exception());

        $this->assertFalse($event->isAllowingCustomResponseCode());
    }
}
Home | Imprint | This part of the site doesn't use cookies.