【发布时间】:2021-04-11 02:11:38
【问题描述】:
我在 Symfony 5 上使用 API,我使用 JMS 序列化程序和 FosRestBundle。我希望我发送的异常是 json 格式,但我已经有了: enter image description hereenter image description here 我和邮递员一起工作
我有一个问题,当我使用 ConstraintViolationList 对发布请求进行约束以验证我的数据时,我会这样做:
`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
{
}
找了一阵子,试了好几个配置都没有发现异常。 它不适用于我的任何例外。 我不知道我是否忘记了设置,但如果有人知道我将不胜感激。 谢谢你,新年快乐!
【问题讨论】:
标签: api symfony exception postman fosrestbundle