website/src/EventSubscriber/ExceptionListener.php

37 lines
1.3 KiB
PHP
Raw Normal View History

2022-04-29 13:51:06 +02:00
<?php
2022-06-08 13:31:17 +02:00
namespace App\EventSubscriber;
2022-04-29 13:51:06 +02:00
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class ExceptionListener
{
public function __construct(UrlGeneratorInterface $router)
{
$this->router = $router;
}
public function onKernelException(ExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getThrowable();
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$route = $this->router->generate('error', ['status' => $exception->getStatusCode()]);
} else {
$route = $this->router->generate('error', ['status' => Response::HTTP_INTERNAL_SERVER_ERROR]);
}
// Customize your response object to display the exception details
$response = new RedirectResponse($route);
// sends the modified response object to the event
$event->setResponse($response);
}
}