error-handler-json
v2.1.0
Published
Express error handlers for JSON APIs
Downloads
1,384
Readme
error-handler-json
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.
Example
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
}
API
.use(errorHandler([options]))
Options
onInternalServerError
- Called when handling anstatus >= 500
error. Default:console.error
includeStack
- Whether to includeerr.stack
as a property in the returned JSON. Default:!production
Errors
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
.