I work on an API on Symfony 5, I use JMS serializer and FosRestBundle.I would like the exceptions that I send to be in json format,But I have already this: enter image description here enter image description here I work with Postman
I have just a problem, when I make a constraint on post request with ConstraintViolationList for validate my data, I do this:
`public function create(User $user, ConstraintViolationList $violations, UserHandler $userHandler)
{
if (count($violations)) {
$message = 'Le JSON envoyé contient des données non valides. Voici les erreurs que vous devez corriger: ';
foreach ($violations as $violation) {
$message .= sprintf("Champ %s: %s ", $violation->getPropertyPath(), $violation->getMessage());
}
throw new ResourceValidationException($message);
}
$user->setCustomer($this->getUser());
$userHandler->addUser($user);
return $this->view(
$user,
Response::HTTP_CREATED,
[
'Location' => $this->generateUrl('app_user_detail', ['id' => $user->getId()], UrlGeneratorInterface::ABSOLUTE_URL),
]
);
}`
I put in the FosRestBundle config, this:
exception:
enabled: true
codes:
{ App\Exception\ResourceValidationException: 400 }
And my all for_rest.yaml:
fos_rest:
view:
formats: { json: true, xml: false, rss: false }
view_response_listener: 'force'
serializer:
serialize_null: true
body_converter:
enabled: true
validate: true
validation_errors_argument: violations
format_listener:
rules:
- { path: ^/, priorities: ['json'], fallback_format: 'json' }
param_fetcher_listener: true
exception:
enabled: true
codes:
{ App\Exception\ResourceValidationException: 400 }
I also created a ResourceValidationException file:
<?php
namespace App\Exception;
class ResourceValidationException extends \Exception
{
}
I've been looking for a while, I tried several configuration for the exception but I was not found. And it doesn't work for any of my exceptions. I don't know if I forgot a setup but if anyone knows how I would be grateful. Thank you and happy new year!
I'm not entirely 100 percent correct on this but I should recommend reading more into FosRestBundle, that it doesn't really work on Symfony 5, but it works on version 4. I tried to implement myself but although with no success. But I'd recommend on reading, because symfony implemented it's own validator:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.