Hapi — transforming “An internal server error occured” into correct Boom errors

In my work i’m using Hapi and Sequelize, and sometimes my sequelize constraints (like unique ones) fails. When this happens, you will get default Boom error for internal server errors and 500 status code, and this is how you can transform this errors into Boom ones:

You only need to do these two things:

  1. Define a onPreResponse hook
  2. Transform an error and return new object if needed or continue with previous request

This is how final code may look like:

// Transform non-boom errors into boom ones
server.ext('onPreResponse', (request, reply) => {
// Transform only server errors
if (request.response.isBoom && request.response.isServer) {
reply(boomify(request.response))
} else {
// Otherwise just continue with previous response
reply.continue()
}
})

Source of boomify function:

function boomify (error) {
// I'm using globals for some things (like sequelize), you should replace it with your sequelize instance
if (error instanceof Core.db.sequelize.UniqueConstraintError) {
let be = Boom.create(400, `child "${error.errors[0].path}" fails because ["${error.errors[0].path}" must be unique]`)
be.output.payload.validation = {
source: 'payload',
keys: error.errors.map(e => e.path)
}
return be
} else {
// If error wasn't found, return default boom internal error
return Boom.internal('An internal server error', error)
}
}

Immolate Improved