An error handler for JSON APIs, meant to be used with http-errors-style errors. The default express
error handler returns HTML, but one might want to instead return JSON when designing a pure API instead of a website.
Note: This is a fork of the unmaintained and archived api-error-handler.
const createError = require('http-errors');
const errorHandler = require('error-handler-json');
app.get('/api/endpoint', (req, res) => {
throw createError(400, 'Invalid data sent');
});
app.use(errorHandler());
A call to /api/endpoint
will return a 400 with the following JSON response:
{
"status": 400,
"message": "Invalid data sent",
"name": "BadRequestError",
"stack": "BadRequestError: ...", // but not in production
}
onInternalServerError
- Called when handling anstatus >= 500
error. Default:console.error
includeStack
- Whether to includeerr.stack
as a property in the returned JSON. Default:!production
4xx errors are exposed to the client. Properties exposed are:
message
status
name
code
type
stack
(optional, seeincludeStack
)- any other own properties of the
Error
object, except forhttp-errors
internals:expose
,statusCode
5xx errors that don't have expose
set to true
are not exposed to the client. Instead, they are given a generic message
as well as the status
.