-
Hi, I'm new to this attribute and also not a pro when it comes to framework specific details, was mostly only using dedicated components for now. Anyway, we're currently looking into migrating a REST API from a combination of FOS Rest Bundle + Sensio Framework Extra using We have a custom error response format that adds additional information about the fields that did not validate by having some helper function in controllers like With
(forgot to tick the "I have research for similar.." checkbox. I did do a bit of a search globally and here :)) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You could use a listener for the ExceptionEvent. Failures in the resolution of arguments with |
Beta Was this translation helpful? Give feedback.
-
Because I was also looking for the same customization. A solution could look like this: <?php
// ...
class ValidationExceptionSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly SerializerInterface $serializer,
) {}
public static function getSubscribedEvents(): array
{
return [
ExceptionEvent::class => 'onExceptionEvent',
];
}
public function onExceptionEvent(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if (!$exception instanceof UnprocessableEntityHttpException) {
return;
}
$validationException = $exception->getPrevious();
if (!$validationException instanceof ValidationFailedException) {
return;
}
$event->setResponse(
new JsonResponse(
data: ['violations' => $this->serializer->toArray($validationException->getViolations())],
status: $exception->getStatusCode(),
),
);
}
} |
Beta Was this translation helpful? Give feedback.
You could use a listener for the ExceptionEvent.
Failures in the resolution of arguments with
MapRequestPayload
will report anHttpException
with a status code 422 (unless yourMapRequestPayload
explicit changes the status code used for validation failure) with aValidationFailedException
(which allows accessing the violation list) as its previous exception. This can allow you to create a custom response for those error.