gpt4 book ai didi

javascript - 如何在 Joi 中捕获验证失败的回调

转载 作者:行者123 更新时间:2023-11-30 12:25:37 25 4
gpt4 key购买 nike

我们正在使用 Hapi 构建网络服务。我们的路线有一些验证。我想知道是否有可能在 hapi 回复客户端之前或之后捕获或覆盖验证失败时的默认回调。

我的(非工作)代码:

{
method: 'GET',
config: {
tags: tags,
validate: {
params: {
id: Joi.number()
.required()
.description('id of object you want to get'),
},
//Tried this, and it's not working:
callback: function(err, value) {
if (err) {
console.log('need to catch errors here!');
}
}
}
},
path: '/model/{id?}',
handler: function(request, reply) {
reply('Ok');
}
}

最佳答案

您可以使用 failAction 属性添加回调:

validate: {
params: {
id: Joi.number()
.required()
.description('id of object you want to get'),
},
failAction: function (request, reply, source, error) {

console.log(error);
}
}

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

failAction - determines how to handle invalid requests. Allowed values are:

  • 'error' - return a Bad Request (400) error response. This is the default value.
  • 'log' - log the error but continue processing the request.
  • 'ignore' - take no action.
  • a custom error handler function with the signature 'function(request, reply, source, error)` where:

    • request - the request object.
    • reply - the continuation reply interface.
    • source - the source of the invalid field (e.g. 'path', 'query', 'payload').
    • error - the error object prepared for the client response (including the validation function error under error.data).

关于javascript - 如何在 Joi 中捕获验证失败的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29515005/

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