src/EventSubscriber/ExceptionSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\DTO\Response\ErrorValidationApi\ErrorValidationApiDTO;
  5. use App\Exception\ErrorValidationException;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Component\Serializer\SerializerInterface;
  11. class ExceptionSubscriber implements EventSubscriberInterface
  12. {
  13.     public function __construct(
  14.         private SerializerInterface $serializer,
  15.     ) {
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             KernelEvents::EXCEPTION => 'onKernelException',
  21.         ];
  22.     }
  23.     public function onKernelException(ExceptionEvent $event): void
  24.     {
  25.         $exception $event->getThrowable();
  26.         $urlPath $event->getRequest()->getPathInfo();
  27.         if (str_starts_with($urlPath'/api/')) {
  28.             // Обработка ошибок валидации для API
  29.             if ($exception instanceof ErrorValidationException) {
  30.                 $responseDto ErrorValidationApiDTO::createFromViolationList(
  31.                     violations$exception->violations,
  32.                     messages$exception->customErrorMessages,
  33.                 );
  34.                 $json $this->serializer->serialize($responseDto'json');
  35.                 $event->setResponse(new JsonResponse(data$jsonstatus400jsontrue));
  36.                 return;
  37.             }
  38.         }
  39.     }
  40. }