简体   繁体   中英

Hapi/Joi validation error log

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.

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

I think better you can give custom error message

{
    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().error(new Error('custom message')),
           name: Joi.string().error(new Error('custom message')),
           status: Joi.string().error(new Error('custom message')),
           index_id: Joi.number().error(new Error('custom message')),
           device_id: Joi.string().error(new Error('custom message')),
           created_at: Joi.string().error(new Error('custom message')),
           updated_at: Joi.string().error(new Error('custom message')),
           sys_version: Joi.string().error(new Error('custom message'))
         }
       }
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM