Search code examples
javascriptnode.jsurl-routinghapi.jsjoi

How to capture callback from failed validation in Joi


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

Solution

  • 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).