How to capture callback from failed validation in Joi

你。 提交于 2019-12-08 04:54:49

问题


We're building a web service using Hapi. Our routes have some validation. I was wondering if it was possible to capture or override the default callback on failed validation, before or after hapi replies to the client.

my (non-working) code:

{
    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');
    }
} 

回答1:


You can use the failAction attribute to add a callback:

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

        console.log(error);
    }
}

For more information see the 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).



回答2:


As I see in API, this maybe done using 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
}


来源:https://stackoverflow.com/questions/29515005/how-to-capture-callback-from-failed-validation-in-joi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!