src/EventSubscriber/DtoExceptionEventSubscriber.php line 15

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Artyum\RequestDtoMapperBundle\Exception\DtoMappingFailedException;
  4. use Artyum\RequestDtoMapperBundle\Exception\DtoValidationFailedException;
  5. use Junker\JSendResponse\JSendFailResponse;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. use Symfony\Component\HttpKernel\KernelEvents;
  9. use Symfony\Component\Serializer\Exception\NotEncodableValueException;
  10. class DtoExceptionEventSubscriber implements EventSubscriberInterface
  11. {
  12.     public function onKernelException(ExceptionEvent $event): void
  13.     {
  14.         $exception $event->getThrowable();
  15.         if (!($exception instanceof DtoMappingFailedException || $exception instanceof DtoValidationFailedException)) {
  16.             return;
  17.         }
  18.         if ($exception instanceof DtoMappingFailedException && $exception->getPrevious() instanceof NotEncodableValueException) {
  19.             $event->setResponse(new JSendFailResponse(
  20.                 'Unable to parse the request body. Please ensure that it is a valid JSON format.',
  21.                 JSendFailResponse::HTTP_BAD_REQUEST
  22.             ));
  23.         }
  24.         if ($exception instanceof DtoValidationFailedException) {
  25.             $errors = [];
  26.             foreach ($exception->getViolations() as $violation) {
  27.                 $errors[$violation->getPropertyPath()][] = $violation->getMessage();
  28.             }
  29.             $event->setResponse(new JSendFailResponse($errorsJSendFailResponse::HTTP_BAD_REQUEST));
  30.         }
  31.     }
  32.     public static function getSubscribedEvents(): array
  33.     {
  34.         return [
  35.             KernelEvents::EXCEPTION => 'onKernelException',
  36.         ];
  37.     }
  38. }