繁体   English   中英

如何捕获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');
    }
} 

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

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

        console.log(error);
    }
}

有关更多信息,请参阅文档

failAction - 确定如何处理无效请求。 允许的值是:

  • 'error' - 返回Bad Request(400)错误响应。 这是默认值。
  • 'log' - 记录错误但继续处理请求。
  • 'ignore' - 不采取任何行动。
  • 一个带有签名'function(request,reply,source,error)`的自定义错误处理函数,其中:

    • request - 请求对象。
    • reply - 继续回复界面。
    • source - 无效字段的来源(例如'path''query''payload' )。
    • error - 为客户端响应准备的错误对象(包括error.data下的验证函数错误)。

正如我在API中看到的,这可能使用failAction完成:

failAction - 定义响应验证失败时要执行的操作。 选项包括:

  • 错误 - 返回内部服务器错误(500)错误响应。 这是默认值。
  • log - 记录错误但发送响应。
failAction: function( source, error, next) {
    // your code
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM