src/EventSubscriber/ExceptionSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Exception\BadRequestApiExceptionInterface;
  4. use App\Exception\NotFoundApiExceptionInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  10. use Symfony\Component\HttpKernel\KernelEvents;
  11. class ExceptionSubscriber implements EventSubscriberInterface
  12. {
  13.     public static function getSubscribedEvents()
  14.     {
  15.         return [
  16.             KernelEvents::EXCEPTION => 'onKernelException',
  17.         ];
  18.     }
  19.     public function onKernelException(ExceptionEvent $event)
  20.     {
  21.         $exception $event->getThrowable();
  22.         $return = [
  23.             'code' => property_exists($exception'getNewCode') ? $exception->getNewCode() : $exception->getCode(),
  24.             'message' => $exception->getMessage(),
  25.         ];
  26.         if ($exception instanceof BadRequestApiExceptionInterface) {
  27.             $event->setResponse(new JsonResponse($returnResponse::HTTP_BAD_REQUEST));
  28.         }
  29.         if ($exception instanceof NotFoundApiExceptionInterface) {
  30.             $event->setResponse(new JsonResponse($returnResponse::HTTP_NOT_FOUND));
  31.         }
  32.         if ($exception instanceof AccessDeniedHttpException) {
  33.             $return['code'] = Response::HTTP_FORBIDDEN;
  34.             $event->setResponse(new JsonResponse($returnResponse::HTTP_FORBIDDEN));
  35.         }
  36.     }
  37. }