2.1.0 • Published 6 months ago

error-handler-json v2.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

error-handler-json

NPM version Build status

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 an status >= 500 error. Default: console.error
  • includeStack - Whether to include err.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, see includeStack)
  • any other own properties of the Error object, except for http-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.

2.1.0

6 months ago

2.0.1

9 months ago

2.0.0

9 months ago

1.0.1

2 years ago