hapi-format-error
v7.0.0
Published
Structure Boom errors into a more desirable format
Downloads
3,193
Maintainers
Readme
hapi-format-error
A plugin to structure Boom errors into a more desirable format.
It currently does the following:
- Returns errors in this format:
{
"error": {
"message": "error message",
"status_code": 400
}
}
- Allows for changing the default Joi validation error status code (400)
- Allows for using a custom server error message
- Allows for logging server errors for debugging purposes
- The final list of error messages is joined with
or
Options
logServerError
: boolean, defaulttrue
- whether server errors (status code >= 500) should be logged to stdoutserverErrorMessage
: string - any custom message you want to return for server errorsjoiStatusCode
: integer - the status code to use instead of400
for Joi validation errorslanguage
: object - language templates used to format specific errors; see below for detailspermeateErrorCode
: boolean, defaultfalse
- whether to surface the.code
property from the Boom Error in the API response
Providing Error Details
Additional error details can optionally be provided in the response object. This allows a client to make decisions based on granular error messages without having to parse the human-readable message
field.
Set permeateErrorCode: true
This will add the .code
property from the Boom Error to the response object. The HTTP response will look like the following:
{
"error": {
"message": "error message",
"status_code": 400,
"code": "unauthorized"
}
}
Language Templates (Message Formatting)
hapi-format-error can massage Joi validation errors into simpler, concise messages. It does this by applying a language template, if available. These are similar to the messages option for Joi validation; the key difference is that they support plural forms.
A simple set of language templates that handle object.unknown
errors would look like this:
{
object: {
unknown: {
singular: '{path} is not allowed',
plural: 'the following parameters are not allowed: {paths}'
}
}
}
hapi-format-error groups messages by their error type, and then looks for matching templates. The plural
template, if provided, is used when more than one error of a given type is reported. If the plural
template is not provided, the singular
template (required) will be applied to each individual error.
Singular templates have the following context variables available:
path
-- the Joi path where the error occurreddetail
-- the Joi validation error detail
Plural templates have a slightly different set of context variables:
paths_str
-- a string containing the Joi paths where this error occurred joined by', '
details
-- an array of the Joi validation error details
If no template is available for an error type, hapi-format-error will return the default Joi error message, stripping surrounding double quotes.