src/EventSubscriber/EventSubscriber.php line 21

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Utils\APIResponse;
  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\HttpExceptionInterface;
  8. class EventSubscriber implements EventSubscriberInterface
  9. {
  10.     public static function getSubscribedEvents(): array
  11.     {
  12.         return array(
  13.             ExceptionEvent::class => 'onKernelException',
  14.         );
  15.     }
  16.     public function onKernelException(ExceptionEvent $event)
  17.     {
  18.         if (preg_match('/^\/api\//'$event->getRequest()->getRequestUri())) {
  19.             $exception $event->getThrowable();
  20.             $statusCode $exception instanceof HttpExceptionInterface $exception->getStatusCode() : APIResponse::$CLIENT_ERROR;
  21.             $response = new APIResponse();
  22.             $response->setStatus($statusCode);
  23.             $response->setContent($exception->getMessage());
  24.             $event->setResponse(new JsonResponse($response$statusCode));
  25.         }
  26.     }
  27. }