src/EventSubscriber/ExceptionSubscriber.php line 12

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\HttpKernel\Event\ExceptionEvent;
  6.     use Symfony\Component\HttpKernel\Exception\HttpException;
  7.     class ExceptionSubscriber implements EventSubscriberInterface
  8.     {
  9.         public function onKernelException(ExceptionEvent $event): void
  10.         {
  11.             // Si on n'est pas sur une route de l'API
  12.             if (!str_contains($event->getRequest()->getPathInfo(), '/api')) {
  13.                 return;
  14.             }
  15.             $exception $event->getThrowable();
  16.             if ($exception instanceof HttpException) {
  17.                 $data = [
  18.                     'status'  => $exception->getStatusCode(),
  19.                     'message' => $exception->getMessage(),
  20.                 ];
  21.             } else {
  22.                 $data = [
  23.                     'status'  => 500// Le status n'existe pas, car ce n'est pas une exception HTTP, donc on met 500 par défaut.
  24.                     'message' => $exception->getMessage(),
  25.                 ];
  26.             }
  27.             $event->setResponse(new JsonResponse($data));
  28.         }
  29.         public static function getSubscribedEvents(): array
  30.         {
  31.             return [
  32.                 'kernel.exception' => 'onKernelException',
  33.             ];
  34.         }
  35.     }