【问题标题】:How to change an error message given by ParamFetcher?如何更改 ParamFetcher 给出的错误消息?
【发布时间】:2015-06-18 22:20:44
【问题描述】:

使用 ParamFetcher 进行验证非常优雅,但错误消息并不漂亮。它包含许多我不想向 api 用户显示的不必要信息。

例如:

"查询参数 parent_id 值 'a' 违反了约束(查询 参数值'a',不符合要求'\d+')"

我想将此消息转换为更简单的消息,例如:“parent_id must be an integer”

我该怎么做?

给出错误的代码如下。而且我看不到任何方法可以提供其他错误消息。

也许还有另一种验证查询参数的替代方案。

$constraint = new Regex(array(
         'pattern' => '#^'.$config->requirements.'$#xsu',
         'message' => sprintf(
                    "%s parameter value '%s', does not match requirements '%s'",
                    $paramType,
                    $param,
                    $config->requirements
         ),
));

源代码:https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Request/ParamFetcher.php#L220

【问题讨论】:

  • 如果我记得,您可以在 requirements 部分使用自定义约束。试试你自己的Regex 类,前缀为'@'

标签: php validation api symfony fosrestbundle


【解决方案1】:

我向 FOSRestBundle 提出了拉取请求以解决此问题https://github.com/FriendsOfSymfony/FOSRestBundle/pull/1015

你可以如下图使用它

@QueryParam(name="parent_id", requirements={"rule" = "\d+", "error_message" = "parent_id must be an integer"}, strict=true, nullable=true, description="Parent Id")

错误信息:

{
    "code": 400,
    "message": "parent_id must be an integer"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-25
    • 2022-10-16
    • 2020-07-10
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多