繁体   English   中英

Symfony 上的 FosRestBundle 5 异常不起作用

[英]FosRestBundle on Symfony 5 Exception don't work

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

我有一个问题,当我使用 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
{
}

我找了一段时间,针对异常尝试了几种配置,但都没有找到。 它不适用于我的任何例外。 我不知道我是否忘记了设置,但如果有人知道我将不胜感激。 谢谢你,新年快乐!

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

验证

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM