<?php
namespace App\EventListener;
use App\Exception\AppException;
use Symfony\Component\HttpFoundation\Response;
use Boab\CmsBundle\View\ViewManagerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class AppExceptionListener
{
private $viewManager;
public function __construct(ViewManagerInterface $viewManager)
{
$this->viewManager = $viewManager;
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
if(!$exception instanceof AppException){
return;
}
$statusCode = ($exception instanceof HttpExceptionInterface) ? $exception->getStatusCode() : $exception->getCode();
$view = $this->viewManager->load(sprintf('exception/exception_%s.html.twig', $statusCode));
$view->exception = $exception;
$response = new Response($view->render());
$response->setStatusCode($statusCode);
$event->setResponse($response);
}
}