src/EventSubscriber/ExceptionSubscriber.php line 13

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use JetBrains\PhpStorm\ArrayShape;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\Exception\HttpException;
  8. class ExceptionSubscriber implements EventSubscriberInterface
  9. {
  10.     public function onExceptionEvent(ExceptionEvent $event): void
  11.     {
  12.         $exception $event->getThrowable();
  13.         if (in_array('application/json'$event->getRequest()->getAcceptableContentTypes(), true)) {
  14.             if ($exception instanceof HttpException) {
  15.                 $data = [
  16.                     'status' => $exception->getStatusCode(),
  17.                     'message' => $exception->getMessage()
  18.                 ];
  19.                 $event->setResponse(new JsonResponse($data));
  20.             } else {
  21.                 $data = [
  22.                     'status' => 500,
  23.                     'message' => $exception->getMessage()
  24.                 ];
  25.                 $event->setResponse(new JsonResponse($data));
  26.             }
  27.         }
  28.     }
  29.     #[ArrayShape([ExceptionEvent::class => "string"])] public static function
  30.     getSubscribedEvents(): array
  31.     {
  32.         return [
  33.              ExceptionEvent::class => 'onExceptionEvent',
  34.         ];
  35.     }
  36. }