<?php
// src/EventListener/ExceptionListener.php
namespace App\EventListener;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ExceptionListener
{
/*
* @var RouterInterface
*/
protected $router;
/*
* HttpNotFoundListener constructor.
* @param Router $router
*/
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function onKernelException(ExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getThrowable();
if ($exception instanceof NotFoundHttpException ||
$exception instanceof AccessDeniedHttpException ) {
// Customize your response object to display the exception details
$response = new RedirectResponse($this->router->generate('app_login'));
// sends the modified response object to the event
$event->setResponse($response);
}
}
}