src/Api/EventSubscriber/ExceptionSubscriber.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\Api\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\Exception\HttpException;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. class ExceptionSubscriber implements EventSubscriberInterface
  10. {
  11.     public function onKernelException(ExceptionEvent $event): void
  12.     {
  13.         $exception $event->getThrowable();
  14.         $request $event->getRequest();
  15.         if (!== strpos($request->getPathInfo(), '/api')) {
  16.             return;
  17.         }
  18.         if ($exception instanceof HttpException) {
  19.             $data = [
  20.                 'status' => $exception->getStatusCode(),
  21.                 'message' => $exception->getMessage(),
  22.             ];
  23.         } else {
  24.             $data = [
  25.                 'status' => Response::HTTP_INTERNAL_SERVER_ERROR,
  26.                 'message' => $exception->getMessage(),
  27.             ];
  28.         }
  29.         $event->setResponse(new JsonResponse($data));
  30.     }
  31.     public static function getSubscribedEvents(): array
  32.     {
  33.         return [
  34.             KernelEvents::EXCEPTION => 'onKernelException',
  35.         ];
  36.     }
  37. }