<?php
namespace App\EventListener;
use App\Exception\JsonSimpleMessageException;
use App\Exception\SimpleMessageException;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ApiExceptionSubscriber implements EventSubscriberInterface
{
/**
* @var ContainerInterface
*/
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::EXCEPTION => 'onKernelException'
);
}
public function onKernelException(ExceptionEvent $event)
{
$e = $event->getThrowable();
if (!$e instanceof JsonSimpleMessageException) {
return;
}
$exceptionCode = $e->getCode() ? $e->getCode() : 500;
$error = array(
'error' => $e->getMessage(),
'code' => $exceptionCode,
'message' => $e->getMessage(),
);
$response = new JsonResponse(
$error,
$exceptionCode
);
$response->headers->set('Content-Type', 'application/problem+json');
$event->setResponse($response);
}
}