【问题标题】:FosRestBundle on Symfony 5 Exception don't workSymfony 5 异常上的 FosRestBundle 不起作用
【发布时间】: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


    【解决方案1】:

    我对此并不完全 100% 正确,但我应该建议阅读更多 FosRestBundle,它在 Symfony 5 上并不能真正工作,但它在版本 4 上工作。我尝试实现自己,但虽然没有成功.但我建议阅读,因为 symfony 实现了它自己的验证器:

    Validation

    【讨论】:

    • 好的,我在 4.4 中降级 Symfony 并且它可以工作
    猜你喜欢
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    • 2019-03-04
    • 2023-02-16
    相关资源
    最近更新 更多