<?php
namespace App\EventListener;
use App\Service\Logger;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class ExceptionListener
{
private UrlGeneratorInterface $urlGenerator;
private Logger $logger;
public function __construct(UrlGeneratorInterface $urlGenerator,
Logger $logger)
{
$this->urlGenerator = $urlGenerator;
$this->logger = $logger;
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$this->logger->writeExceptionLog($exception);
if ($exception instanceof AccessDeniedHttpException) {
$response = new RedirectResponse($this->urlGenerator->generate('error403'));
} elseif ($exception instanceof NotFoundHttpException) {
$response = new RedirectResponse($this->urlGenerator->generate('error404'));
} else {
if($_ENV['APP_ENV'] == 'dev') return;
$response = new RedirectResponse($this->urlGenerator->generate('error'));
}
$event->setResponse($response);
}
}