Reputation: 5795
I'm building a simple REST api with Symfony 7 and using MapRequestPayload
attribute to automatically map request data into an object. Validation is also handled automatically with symfony/validator.
// a controller method
use App\Request\TestRequest
public function example(#[MapRequestPayload] TestRequest $testRequest): JsonResponse
{
// validation is handled automatically, safely use $testRequest object...
}
This works great, except I would like to return a json response simpler than what symfony is automatically returning.
To do that, I've created a listener to catch ValidationFailedException
s and set the response there. But apparently, my listener only gets handed a HttpException
. In order to catch ValidationFailedException
, I use getPrevious()
method and check if it is a ValidationFailedException
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
$prevException = $exception->getPrevious();
if ($exception instanceof HttpException && $prevException instanceof ValidationFailedException) {
// create a custom json response using $prevException->getViolations()
...
}
This works, but since I'm new to Symfony, I'm not sure this is the right way or even a reliable way to achieve this.
Opinions?
Upvotes: 0
Views: 393