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

How to capture callback from failed validation in Joi

我们正在使用 Hapi 构建 Web 服务。我们的路线有一些验证。我想知道是否有可能在 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');
    }
} 

正如我在 API 中看到的那样,这可能是使用 failAction:

完成的

failAction - defines what to do when a response fails validation. Options are:

  • error - return an Internal Server Error (500) error response. This is the default value.
  • log - log the error but send the response.
failAction: function( source, error, next) {
    // your code
}

您可以使用 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).