Express.js Development Error Handler
The `errorhandler` middleware is a development-only utility for Express.js applications, designed to display detailed error information during local development. It is currently at version `1.5.2` and has a slow, maintenance-focused release cadence, primarily addressing dependency updates and minor chores. Its core functionality involves robust content negotiation (HTML, JSON, plain text) to present error stack traces and object details to the client when an error occurs. A key differentiator is its explicit intent for development environments, as it exposes sensitive server-side information, making it unsuitable for production use. It handles both standard `Error` objects and generic JavaScript objects, using `util.inspect` for non-Error objects to provide comprehensive debugging insights.
Common errors
-
Error: Can't set headers after they are sent to the client
cause This error occurs when a previous middleware or route handler attempts to send a response or set headers *before* an error is thrown and caught by `errorhandler`. If `errorhandler` then tries to send its own error response, the headers have already been sent.fixEnsure that response logic in your middleware and routes is robust and does not send multiple responses. If an error occurs, call `next(err)` and let the error handling middleware take over. Avoid `res.send()` or `res.end()` followed by `next(err)` in the same block. -
TypeError: app.use is not a function
cause This indicates you are trying to use `app.use()` on an object that is not an Express or Connect application instance. This might happen if you are using a plain HTTP server without proper middleware setup.fixMake sure `app` is initialized as an Express or Connect application, e.g., `const express = require('express'); const app = express();` or `const connect = require('connect'); const app = connect();`.
Warnings
- breaking The `log` option's default behavior changed in `1.5.0`. Previously, it would always log to `console.error`. Now, if `process.env.NODE_ENV === 'test'`, the default `log` value becomes `false` (no console logging). Explicitly set `log: true` to force console logging in 'test' environments.
- gotcha This middleware is strictly for development environments. It exposes full error stack traces and internal details of any object passed as an error, which can be a severe security vulnerability if used in production.
- gotcha The `log` option function is invoked *after* the response has been written. This means attempting to modify the response (e.g., setting headers, sending a different body) within the custom `log` function will have no effect.
- gotcha When a non-`Error` object is passed as an error (e.g., `next('something broke')` instead of `next(new Error('something broke'))`), `errorhandler` will attempt to display its contents using `util.inspect`. While useful for debugging, this might expose unexpected or very verbose object structures.
Install
-
npm install errorhandler -
yarn add errorhandler -
pnpm add errorhandler
Imports
- errorhandler
import errorhandler from 'errorhandler'
const errorhandler = require('errorhandler') - errorHandlerMiddleware
app.use(new errorhandler())
app.use(errorhandler())
- logOption
app.use(errorhandler({ logger: customLogger }))app.use(errorhandler({ log: customLogger }))
Quickstart
const connect = require('connect');
const errorhandler = require('errorhandler');
const notifier = require('node-notifier');
const app = connect();
// Assumes NODE_ENV is set by the user, e.g., via 'NODE_ENV=development node app.js'
if (process.env.NODE_ENV === 'development') {
// Only use in development to display detailed error information
app.use(errorhandler({
log: (err, str, req, res) => {
// Custom logging function, e.g., sending system notifications
const title = `Error in ${req.method} ${req.url}`;
notifier.notify({
title: title,
message: str,
// Optionally, add a sound or icon for better visibility
sound: true,
wait: true
});
// Also log to console for standard debugging flow
console.error(str);
}
}));
}
// Example route that intentionally throws an error
app.use('/error', (req, res, next) => {
next(new Error('This is a simulated error for demonstration!'));
});
// Fallback for non-error requests
app.use((req, res, next) => {
res.end('Hello from a non-error path. Try /error to see the error handler in action.');
});
const port = 3000;
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
console.log('Ensure NODE_ENV is set to \'development\' to enable errorhandler.');
});