簡體   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