src\EventListener\ExceptionListener.php line 28

Open in your IDE?
  1. <?php
  2. // src/EventListener/ExceptionListener.php
  3. namespace App\EventListener;
  4. use Symfony\Component\Routing\RouterInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  8. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  9. class ExceptionListener
  10. {
  11.     /*
  12.      * @var RouterInterface
  13.      */
  14.     protected $router;
  15.     /*
  16.      * HttpNotFoundListener constructor.
  17.      * @param Router $router
  18.      */
  19.     public function __construct(RouterInterface $router)
  20.     {
  21.         $this->router $router;
  22.     }
  23.     public function onKernelException(ExceptionEvent $event)
  24.     {
  25.         // You get the exception object from the received event
  26.         $exception $event->getThrowable();
  27.         if ($exception instanceof NotFoundHttpException ||
  28.             $exception instanceof AccessDeniedHttpException ) {
  29.             // Customize your response object to display the exception details
  30.             $response = new RedirectResponse($this->router->generate('app_login'));
  31.             // sends the modified response object to the event
  32.             $event->setResponse($response);
  33.         }
  34.     }
  35. }