src/EventListener/ExceptionListener.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Service\Logger;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  7. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  8. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  9. class ExceptionListener
  10. {
  11. private UrlGeneratorInterface $urlGenerator;
  12. private Logger $logger;
  13. public function __construct(UrlGeneratorInterface $urlGenerator,
  14. Logger $logger)
  15. {
  16. $this->urlGenerator = $urlGenerator;
  17. $this->logger = $logger;
  18. }
  19. public function onKernelException(ExceptionEvent $event): void
  20. {
  21. $exception = $event->getThrowable();
  22. $this->logger->writeExceptionLog($exception);
  23. if ($exception instanceof AccessDeniedHttpException) {
  24. $response = new RedirectResponse($this->urlGenerator->generate('error403'));
  25. } elseif ($exception instanceof NotFoundHttpException) {
  26. $response = new RedirectResponse($this->urlGenerator->generate('error404'));
  27. } else {
  28. if($_ENV['APP_ENV'] == 'dev') return;
  29. $response = new RedirectResponse($this->urlGenerator->generate('error'));
  30. }
  31. $event->setResponse($response);
  32. }
  33. }