I'm developing an API using hapi js and couchbase. I'm using log4js to log the errors.
{
// Add a user level
method: 'POST',
path: '/api/v1/userlevel',
config: {
handler: (request, reply) => {
const userlevel = new Userlevel(request.payload);
userlevel.save((err) =>{
if(err) {
return reply({
status: 400,
message: err.message
}).code(400);
// logger.error(err);
}
// logger.debug(reply);
return reply(userlevel).code(201);
});
},
validate: {
payload: {
group_id: Joi.string(),
name: Joi.string(),
status: Joi.string(),
index_id: Joi.number(),
device_id: Joi.string(),
created_at: Joi.string(),
updated_at: Joi.string(),
sys_version: Joi.string()
}
}
}
}
when i'm sending a POST request to this endpoint with invalid data it is showing an error
POST request
{
"group_id" : "test1",
"name" : "test1",
"status":"test1",
"index_id":1,
"device_id":"test1",
"created_at":7,
"updated_at":7,
"sys_version":7
}
error
{"statusCode":400,"error":"Bad Request","message":"child \"created_at\" fails because [\"created_at\" must be a string]","validation":{"source":"payload","keys":["created_at"]}}
I need to log this error message. I have tried to find the place which this message is generating. But i couldn't find it. Please help. Thank you in advance.
This package has been deprecated.
Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.
I would strongly recommend using joi on the frontend now as you can share schemas between frontend and backend, which is really fantastic.
If you're willing to migrate to Hapi 17 the following will work. There may well be a similar Hapi 16 solution if you have a dig through the documentation.
There's a failAction
callback method you can hook into if a route validation fails, here seems the best place to log your error.
const config = {
routes: {
validate: {
failAction: async (request, h, err) =>
{
if (err.isJoi)
{
// do something with error
console.log(err.message);
}
throw err;
}
}
}
};
const server = new Hapi.Server(config);
You can achieve this almost the same way with Hapi 16, see below :
server.route({
method: 'GET',
path: '/what/ever,
handler: function(request, reply) {
},
config: {
validate: {
payload: {},
failAction: function(request, reply, source, error) {
// do your stuff here
// you should also reply something
}
}
});
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