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

Befriending Hapi and Boom

Warning

This post was written more than 5 years ago, and its contents may be out of date

An example of resulting error:

{
"statusCode": 400,
"error": "Bad Request",
"message": "child \"email\" fails because [\"email\" must be unique]",
"validation": {
"source": "payload",
"keys": [
"email"
]
}
]

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) {
if (error instanceof 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)
}
}
Licensed under CC BY-NC 4.0

Comments