如何在hapi.js中自定义验证错误响应?

时间:2015-04-10 22:36:28

标签: node.js hapijs

使用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"
        ]
    }
}

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

1 个答案:

答案 0 :(得分:23)

有两种方法可以自定义输出:

  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();
    });
    
  3. 有关详细信息,请参阅API documentation