src/EventListener/ExceptionListener.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Twig\Environment;
  9. class ExceptionListener implements EventSubscriberInterface {
  10.     protected $twig;
  11.     public function __construct(Environment $twig) {
  12.         $this->twig $twig;
  13.     }
  14.     public function onKernelException(ExceptionEvent $event) {
  15.         $exception $event->getThrowable();
  16.         if ($exception instanceof NotFoundHttpException) {
  17.             $response = new Response();
  18.             $response->setContent($this->twig->render('shared/404.html.twig'));
  19.             $response->setStatusCode($exception->getStatusCode());
  20.             $response->headers->replace($exception->getHeaders());
  21.             $event->setResponse($response);
  22.         }
  23.     }
  24.     public static function getSubscribedEvents() {
  25.         return array(
  26.             KernelEvents::EXCEPTION => 'onKernelException'
  27.         );
  28.     }
  29. }