<?php
namespace App\EventSubscriber;
use Artyum\RequestDtoMapperBundle\Exception\DtoMappingFailedException;
use Artyum\RequestDtoMapperBundle\Exception\DtoValidationFailedException;
use Junker\JSendResponse\JSendFailResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
class DtoExceptionEventSubscriber implements EventSubscriberInterface
{
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (!($exception instanceof DtoMappingFailedException || $exception instanceof DtoValidationFailedException)) {
return;
}
if ($exception instanceof DtoMappingFailedException && $exception->getPrevious() instanceof NotEncodableValueException) {
$event->setResponse(new JSendFailResponse(
'Unable to parse the request body. Please ensure that it is a valid JSON format.',
JSendFailResponse::HTTP_BAD_REQUEST
));
}
if ($exception instanceof DtoValidationFailedException) {
$errors = [];
foreach ($exception->getViolations() as $violation) {
$errors[$violation->getPropertyPath()][] = $violation->getMessage();
}
$event->setResponse(new JSendFailResponse($errors, JSendFailResponse::HTTP_BAD_REQUEST));
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
}