【问题标题】:How can I customize the validation error response in hapi.js?如何在 hapi.js 中自定义验证错误响应?
【发布时间】:2015-06-16 18:41:33
【问题描述】:

当使用config.validate option on a route 并且请求由于验证而失败时,hapi 返回如下错误:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "child \"weight\" fails because [\"weight\" is required]",
    "validation": {
        "source": "payload",
        "keys": [
            "weight"
        ]
    }
}

有没有办法发送不同格式的验证错误?

【问题讨论】:

  • 能否发布您在路由规范中使用的 config.validate 对象?

标签: node.js hapijs


【解决方案1】:

自定义输出有两种方式:

  1. config.validate 中使用failAction 属性:

    config: {
        validate: {
            params: {
                name: Joi.string().min(3).max(10)
            },
            failAction: function (request, reply, source, error) {
    
                error.output.payload.message = 'custom';
                return reply(error).code(400);
            }
        }
    }
    
  2. 使用onPreResponse 扩展点:

    server.ext('onPreResponse', function (request, reply) {
    
        var response = request.response;
        if (response.isBoom && response.data.name === 'ValidationError') {
            response.output.payload.message = 'custom';
        }
    
        return reply.continue();
    });
    

有关详细信息,请参阅API documentation

【讨论】:

  • 在第一个示例中,我不得不省略 .code(400) 部分,因为当向回复函数提供错误对象时,code() 函数不存在于由 @ 返回的对象中987654331@。传递给reply()的错误对象自动将响应代码设置为400。
猜你喜欢
  • 2018-12-28
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 2022-10-07
  • 1970-01-01
  • 2017-09-24
  • 2018-06-17
相关资源
最近更新 更多