sajad torkamani

When is it dispatched?

Dispatched as soon as an error occurs during the handling of an HTTP request (i.e., in HttpKernel::handle). Internally, the body of the handle() method is wrapped in a try-catch block.

When an exception is thrown, the kernel.exception event is dispatched so that your system can deal with the exception however it needs to. See here for the relevant source code.

Use cases

  • Recover from certain types of exceptions and return an appropriate response.
  • Modifying the exception details sent in the response.

Example

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;

public function onKernelException(ExceptionEvent $event)
{
    $exception = $event->getThrowable();
    $response = new Response();
    // setup the Response object based on the caught exception
    $event->setResponse($response);

    // you can alternatively set a new Exception
    // $exception = new \Exception('Some special exception');
    // $event->setThrowable($exception);
}

List event listeners

php bin/console debug:event-dispatcher kernel.exception

Sources / related

Tagged: Symfony

Leave a comment

Your email address will not be published. Required fields are marked *