src/EventSubscriber/ExceptionSubscriber.php line 28

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\HttpKernel\KernelEvents;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  9. class ExceptionSubscriber implements EventSubscriberInterface
  10. {
  11.     public function __construct(
  12.         private UrlGeneratorInterface $urlGenerator
  13.     )
  14.     {
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             KernelEvents::EXCEPTION => 'onException',
  20.         ];
  21.     }
  22.     
  23.     public function onException(ExceptionEvent $event): void
  24.     {
  25.         $exception $event->getThrowable();
  26.         $statusCode 0;
  27.         if ($exception instanceof HttpExceptionInterface) {
  28.             $statusCode $exception->getStatusCode();
  29.         }
  30.         if($statusCode === 404 && $_ENV['APP_ENV'] !== 'dev'){
  31.             $event->setResponse(new RedirectResponse($this->urlGenerator->generate('404_exception')));
  32.         }
  33.         elseif($_ENV['APP_ENV'] !== 'dev'){
  34.             $event->setResponse(new RedirectResponse($this->urlGenerator->generate('500_exception')));
  35.         }
  36.     }
  37. }