【问题标题】:How to capture callback from failed validation in Joi如何从 Joi 中的验证失败中捕获回调
【发布时间】:2015-06-13 10:22:13
【问题描述】:

我们正在使用 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');
    }
} 

【问题讨论】:

    标签: javascript node.js url-routing hapijs joi


    【解决方案1】:

    您可以使用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 - 确定如何处理无效请求。允许的值为:

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

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

    【讨论】:

      【解决方案2】:

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

      failAction - 定义当响应验证失败时要做什么。 选项是:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-03
        • 2013-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-10
        • 2020-05-26
        • 2017-07-05
        相关资源
        最近更新 更多