src/EventSubscriber/ApiExceptionSubscriber.php line 24

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  9. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  10. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  11. use Symfony\Component\Serializer\SerializerInterface;
  12. class ApiExceptionSubscriber implements EventSubscriberInterface
  13. {
  14.     private $serializer;
  15.     public function __construct(SerializerInterface $serializer)
  16.     {
  17.         $this->serializer $serializer;
  18.     }
  19.     public function onKernelException(ExceptionEvent $event)
  20.     {
  21.         if ($_ENV['APP_ENV'] == 'prod' && $event->getThrowable() instanceof NotFoundHttpException) {
  22.             $response = new RedirectResponse('/');
  23.             $event->setResponse($response);
  24.         } else {
  25.             $json $this->serializer->serialize($event'json');
  26.             $resHeaders = ['Content-Type' => 'application/json''Access-Control-Allow-Origin' => '*'];
  27.             if ($event->getThrowable() instanceof HttpExceptionInterface) {
  28.                 $code $event->getThrowable()->getStatusCode();
  29.                 if ($event->getThrowable() instanceof UnauthorizedHttpException) {
  30.                     $resHeaders array_merge($resHeaders$event->getThrowable()->getHeaders());
  31.                 }
  32.             } else {
  33.                 $code Response::HTTP_INTERNAL_SERVER_ERROR;
  34.             }
  35.             $response = new JsonResponse($json$code$resHeaderstrue);
  36.             $event->setResponse($response);
  37.         }
  38.     }
  39.     public static function getSubscribedEvents()
  40.     {
  41.         return [
  42.             'kernel.exception' => 'onKernelException',
  43.         ];
  44.     }
  45. }