gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:14:23 26 4
gpt4 key购买 nike

使用 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. 使用 failAction config.validate 中的属性:

    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了解更多详情。

关于node.js - 如何在 hapi.js 中自定义验证错误响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29571703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com