Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I customize the validation error response in hapi.js?

Tags:

node.js

hapijs

When using the config.validate option on a route and a request fails due to validation, hapi returns an error like:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "child \"weight\" fails because [\"weight\" is required]",
    "validation": {
        "source": "payload",
        "keys": [
            "weight"
        ]
    }
}

Is there a way to send a different formatted validation error?

like image 455
JeremiahLee Avatar asked Apr 10 '15 22:04

JeremiahLee


People also ask

What is Joi validation?

Hapi Joi is an object schema description language and validator for JavaScript objects. With Hapi Joi, we create blueprints or schemas for JavaScript objects (an object that stores information) to ensure validation of key information.

What is Hapi?

Hapi, in ancient Egyptian religion, personification of the annual inundation of the Nile River. Hapi was the most important among numerous personifications of aspects of natural fertility, and his dominance increased during Egyptian history.


1 Answers

There are two ways to customize the output:

  1. Using the failAction attribute in config.validate:

    config: {
        validate: {
            params: {
                name: Joi.string().min(3).max(10)
            },
            failAction: function (request, reply, source, error) {
    
                error.output.payload.message = 'custom';
                return reply(error).code(400);
            }
        }
    }
    
  2. Using the onPreResponse extension point:

    server.ext('onPreResponse', function (request, reply) {
    
        var response = request.response;
        if (response.isBoom && response.data.name === 'ValidationError') {
            response.output.payload.message = 'custom';
        }
    
        return reply.continue();
    });
    

See the API documentation for more details.

like image 140
Gergo Erdosi Avatar answered Oct 16 '22 00:10

Gergo Erdosi