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?
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.
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.
There are two ways to customize the output:
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);
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With