<?php
namespace Boab\CmsBundle\EventListener;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;
use Boab\CmsBundle\Exception\ApiException;
class ApiExceptionListener
{
private $serializer;
public function __construct(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}
public function onKernelException(ExceptionEvent $event)
{
$request = $event->getRequest();
$exception = $event->getThrowable();
$format = $request->getContentType();
if(!$exception instanceof ApiException){
return;
}
$data = $this->serializer->normalize($exception, $format);
$response = new JsonResponse($data);
$response->setStatusCode($data['code']);
$event->setResponse($response);
}
}