<?php
namespace Boab\CmsBundle\Api\EventListener;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Boab\CmsBundle\Api\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);
}
}