Basic error handler for express. This middleware shows errors according to the "Accept" header. It will shutdown app in case of uncaught error.
npm install express-err
var express = require('express');
var errorHandler = require('express-err');
var app = express();
// Basic route.
app.get('/', function (req, res) {
res.send('Hello world!');
});
// Redirect other routes to 404.
app.use(errorHandler.httpError(404));
// Handle errors.
app.use(errorHandler());
The error handler middleware is used to display errors and shutdown app in case of uncaught error.
The avalaible options are :
Default view to render in case of error. Defaults to "view"
.
app.use(errorHandler({ view: 'my/custom/error-view' }));
Tell to the process to exit on uncaught exceptions. Defaults to true
.
app.use(errorHandler({ exitOnUncaughtException: false }));
The code used to exit app in case of uncaught exception. Defaults to 1
.
app.use(errorHandler({ exitCode: 2 }));
The default HTTP error code. Defaults to '500'.
app.use(errorHandler({ status: 500 }));
The supported error formatters. Defaults to JSON, HTML and plain text.
app.use(errorHandler({ formatters: ['json', 'text', 'html'] }));
If your express app does not serve HTML, you might want to limit the supported error response types:
app.use(errorHandler({ formatters: ['json', 'text'] }));
You can also define a default formatter that will be used if your app does not support the request 'Accept' type. Defaults to 'text'.
app.use(errorHandler({ defaultFormatter: 'json' }));
You can use httpError to return a custom error with a status and a message.
MIT