src/EventSubscriber/ApiExceptionSubscriber.php line 13

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\BadRequestHttpException;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class ApiExceptionSubscriber implements EventSubscriberInterface
  9. {
  10.     public function onKernelException(ExceptionEvent $event)
  11.     {
  12.         $e $event->getThrowable();
  13.         if (!$e instanceof BadRequestHttpException) {
  14.             return;
  15.         }
  16.         $response = new JsonResponse(
  17.             ['errors' => $e->getMessage()],
  18.             $e->getStatusCode()
  19.         );
  20.         $event->setResponse($response);
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             KernelEvents::EXCEPTION => 'onKernelException',
  26.         ];
  27.     }
  28. }