<?php
namespace App\EventSubscriber;
use App\Exception\BadRequestApiExceptionInterface;
use App\Exception\NotFoundApiExceptionInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class ExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
$return = [
'code' => property_exists($exception, 'getNewCode') ? $exception->getNewCode() : $exception->getCode(),
'message' => $exception->getMessage(),
];
if ($exception instanceof BadRequestApiExceptionInterface) {
$event->setResponse(new JsonResponse($return, Response::HTTP_BAD_REQUEST));
}
if ($exception instanceof NotFoundApiExceptionInterface) {
$event->setResponse(new JsonResponse($return, Response::HTTP_NOT_FOUND));
}
if ($exception instanceof AccessDeniedHttpException) {
$return['code'] = Response::HTTP_FORBIDDEN;
$event->setResponse(new JsonResponse($return, Response::HTTP_FORBIDDEN));
}
}
}