How to handle hapi validation errors?


How to handle hapi validation errors?



I have following route code for hapi...


const routeConfig = {
method: 'POST',
path: '/user',
config: {
validate: {
payload: {
firstName: Joi.string().required(),
}
},
handler
}
}



So when I don't pass the firstName it throws error like this


firstName


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



Now, I need to handle the above error in catch


const handler = async(request, reply) => {
try {
const payload = request.payload
const createUser = await User.create(payload)
let token = Helpers.createJwt(createUser)
reply({ success: true, message: 'User created successFully', token })
} catch(err) {
// need to do something here to handle the error like
if (err) {
reply ({ error: "firstName is required", message: "Signup unsuccessfull" })
}
}
}




2 Answers
2



There is a much better solution:


config: {
validate: {
payload: {
firstName: Joi.string().required(),
},
failAction(request, reply, source, error) {
reply({
error: 'badRequest',
}).code(400);
},
},
},



If the Joi validation fails, it will trigger the failAction and you will be able to handle the error (sending it to log service and/or return a specific message).



It's a bit hidden in the doc but here is the relevant part



I must confess, I did'nt tried it with hapi 17...





That's what I wanted to do... Perfect man
– Anthony Winzlet
May 14 at 16:21






Glad I could help
– Ernest Jones
May 14 at 16:23





Your right... And the documentation is not really clear on this point
– Ernest Jones
May 14 at 16:25





Thank you Ernest
– Anthony Winzlet
May 14 at 16:26





Your welcome Ashish ^^
– Ernest Jones
May 14 at 16:27



Maybe you should try with something like this ?


const routeConfig = {
method: 'POST',
path: '/user',
config: {
validate: {
payload: {
firstName: Joi.string().required().error(new Error('firstName is required')),
}
},
handler
}
}



Take a look on this page here



Hope it helps.





Thank you Sparw... is there any better way to do it?
– Anthony Winzlet
May 14 at 6:34





I'm not sure there is a better way to do that properly.. :/
– Sparw
May 14 at 7:37






your answer helps me to change the message and Ernest's answer helps me to return that messsage... So thanks it works...
– Anthony Winzlet
May 19 at 6:45






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV