Custom Boom error messages

Atlante Avila picture Atlante Avila · Jul 19, 2017 · Viewed 8k times · Source

On my Hapi.js server, I'd like to send a specific message if an account does not have permission rights to access an api endpoint. The Boom message I have right now looks like this:

return reply(Boom.unauthorized("unauthorized access to this API."));

This returns a message that looks like this:

{
  "statusCode": 401,
  "error": "Unauthorized",
  "message": "unauthorized access to this API."
}

I would like to make it more customized to look like this:

{
  "success": false,
  "message": "unauthorized access to this API.",
  "csrf-decorator": "",
  "redirect": ""
}

Do we have access to customize the Boom error messages?

Thanks!

Answer

Atlante Avila picture Atlante Avila · Jul 19, 2017

Boom comes with built in response error transformation. So in order to achieve my results I had reformat my error reply in the following way:

const error = Boom.forbidden("Sorry, you are restricted in accesssing this API. No soup for you!.");
error.output.statusCode = 403;    // Assign a custom error code
error.output.payload["csrf-decorator"] = request.headers["csrf-decorator"];
error.reformat();
return reply(error);