src/Bundles/ApiBundle/EventSubscriber/ExceptionSubscriber.php line 25

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Bundles\ApiBundle\EventSubscriber;
  4. use App\Bundles\ApiBundle\v1\JsonResponse;
  5. use App\Platform\Exception\ConstraintViolationException;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class ExceptionSubscriber implements EventSubscriberInterface
  11. {
  12.     public static function getSubscribedEvents(): array
  13.     {
  14.         return [
  15.             KernelEvents::EXCEPTION => [
  16.                 ['onKernelException'0],
  17.             ],
  18.         ];
  19.     }
  20.     public function onKernelException(ExceptionEvent $event): void
  21.     {
  22.         $throwable $event->getThrowable();
  23.         if (!str_starts_with($event->getRequest()->getPathInfo(), '/api')) {
  24.             return;
  25.         }
  26.         if ($throwable instanceof ConstraintViolationException) {
  27.             $event->setResponse(JsonResponse::validationError($throwable->getErrors(), $throwable->getCode()));
  28.         }
  29.         if (!$throwable instanceof HttpExceptionInterface) {
  30.             return;
  31.         }
  32.         $event->setResponse(JsonResponse::error($throwable->getStatusCode(), $throwable->getMessage()));
  33.     }
  34. }