2.1.0 • Published 2 years ago
error-handler-json v2.1.0
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 >= 500error. Default:console.errorincludeStack- Whether to includeerr.stackas a property in the returned JSON. Default:!production
Errors
4xx errors are exposed to the client. Properties exposed are:
messagestatusnamecodetypestack(optional, seeincludeStack)- any other own properties of the
Errorobject, except forhttp-errorsinternals: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.