<?php

namespace App\EventSubscriber;

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);
    }
}