问题描述
我在 Symfony 5 上开发 API,我使用 JMS 序列化程序和 FosRestBundle。我希望我发送的异常为 json 格式,但我已经有了: enter image description hereenter image description here 我和邮递员一起工作
我有一个问题,当我使用 ConstraintViolationList 对 post 请求进行约束以验证我的数据时,我这样做:
`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),]
);
}`
我输入了 FosRestBundle 配置,这个:
exception:
enabled: true
codes:
{ App\Exception\ResourceValidationException: 400 }
还有我所有的 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 }
我还创建了一个 ResourceValidationException 文件:
<?php
namespace App\Exception;
class ResourceValidationException extends \Exception
{
}
找了好久,针对异常尝试了几种配置,都没有找到。 它对我的任何例外都不起作用。 我不知道我是否忘记了设置,但如果有人知道我会如何感激。 谢谢你,新年快乐!
解决方法
我并不完全 100% 正确,但我应该建议更多地阅读 FosRestBundle,它实际上不适用于 Symfony 5,但它适用于版本 4。我尝试实现自己,但没有成功.但我建议阅读,因为 symfony 实现了它自己的验证器: