<?php
namespace App\Event;
use App\Exception\Core\ConfigurationException;
use Doctrine\DBAL\Exception\ConnectionException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Twig\Environment;
class ExceptionListener
{
protected $twig;
public function __construct(Environment $twig)
{
$this->twig = $twig;
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
$context = ['message' => $exception->getMessage()];
$response = new Response();
if($exception instanceof AccessDeniedHttpException)
$response->setContent($this->twig->render('exception/access_denied.html.twig', $context));
if($exception instanceof ConfigurationException)
$response->setContent($this->twig->render('exception/configuration.html.twig', $context));
if($exception instanceof ConnectionException)
$response->setContent($this->twig->render('exception/db_connection.html.twig', $context));
if($exception instanceof NotFoundHttpException)
$response->setContent($this->twig->render('exception/404.html.twig', $context));
if($response->getContent())
$event->setResponse($response);
}
}