Rico's Blog

Back

Joi validation is powerful and easy to work with, however it’s not always obvious or easy to add stuff like error code(s) to the hapijs response. This post will show you a way (or two) to deal with that problem.

Step 1, assign error codes to each validation error#

Quick example:

Step 2, customize failAction when creating Hapi server#

Step 3, customize response#

The reason this step is needed is because Hapi would strip out the injected errorCode attribute created by step 2

server.ext('onPreResponse', (request, h) => {
  const response = request.response
  if (!response.isBoom) {
    return h.continue
  }
  const { data } = response
  if (data !== undefined) {
    response.output.payload = {
      ...response.output.payload,
      ...data
    }
  }
  return h.continue
})
javascript

With the above setup, request

curl http://localhost:3000/person -d ''
bash

would result in

{"statusCode":400,"error":"Bad Request","message":"child \"firstName\" fails because [Firstname should not be empty!]","errorCode":111}
json

By default abortEarly: true is set Hapi, if multiple error codes are desired, only Step 2 needs to be adjusted to

request

curl http://localhost:3000/person -d 'firstName='
bash

would return

{"statusCode":400,"error":"Bad Request","message":"child \"firstName\" fails because [Firstname should not be empty!, Firstname should have at least 5 characters!]","errorCodes":[111,121]}
json

If you need to add error code in your application code, you can simply achieve that by returning a Boom like the following

return Boom.badRequest('Your error message here', { errorCode: YOUR_CODE })
javascript

I’ve composed a gist in case you want to save some typings in trying out the code. Cheers!