{"id":17003,"library":"errorhandler","title":"Express.js Development Error Handler","description":"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.","status":"maintenance","version":"1.5.2","language":"javascript","source_language":"en","source_url":"https://github.com/expressjs/errorhandler","tags":["javascript"],"install":[{"cmd":"npm install errorhandler","lang":"bash","label":"npm"},{"cmd":"yarn add errorhandler","lang":"bash","label":"yarn"},{"cmd":"pnpm add errorhandler","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for content negotiation to determine the response format (HTML, JSON, text) for error details.","package":"accepts","optional":false},{"reason":"Indirectly used via 'accepts' for MIME type parsing and handling during content negotiation.","package":"mime-types","optional":false},{"reason":"Indirectly used via 'accepts' to negotiate the best content type for the error response.","package":"negotiator","optional":false},{"reason":"Used to safely escape HTML content when rendering error details in HTML responses.","package":"escape-html","optional":false}],"imports":[{"note":"This package is CommonJS-first and primarily used with `require()`. While Node.js allows `import errorhandler from 'errorhandler'` in ESM contexts, the official examples use `require`.","wrong":"import errorhandler from 'errorhandler'","symbol":"errorhandler","correct":"const errorhandler = require('errorhandler')"},{"note":"The `errorhandler` function itself returns the middleware; it's not a class that needs `new`.","wrong":"app.use(new errorhandler())","symbol":"errorHandlerMiddleware","correct":"app.use(errorhandler())"},{"note":"The option to provide a custom logging function is named `log`, not `logger`.","wrong":"app.use(errorhandler({ logger: customLogger }))","symbol":"logOption","correct":"app.use(errorhandler({ log: customLogger }))"}],"quickstart":{"code":"const connect = require('connect');\nconst errorhandler = require('errorhandler');\nconst notifier = require('node-notifier');\n\nconst app = connect();\n\n// Assumes NODE_ENV is set by the user, e.g., via 'NODE_ENV=development node app.js'\nif (process.env.NODE_ENV === 'development') {\n  // Only use in development to display detailed error information\n  app.use(errorhandler({\n    log: (err, str, req, res) => {\n      // Custom logging function, e.g., sending system notifications\n      const title = `Error in ${req.method} ${req.url}`;\n      notifier.notify({\n        title: title,\n        message: str,\n        // Optionally, add a sound or icon for better visibility\n        sound: true, \n        wait: true\n      });\n      // Also log to console for standard debugging flow\n      console.error(str);\n    }\n  }));\n}\n\n// Example route that intentionally throws an error\napp.use('/error', (req, res, next) => {\n  next(new Error('This is a simulated error for demonstration!'));\n});\n\n// Fallback for non-error requests\napp.use((req, res, next) => {\n  res.end('Hello from a non-error path. Try /error to see the error handler in action.');\n});\n\nconst port = 3000;\napp.listen(port, () => {\n  console.log(`Server running on http://localhost:${port}`);\n  console.log('Ensure NODE_ENV is set to \\'development\\' to enable errorhandler.');\n});","lang":"javascript","description":"This example demonstrates how to integrate `errorhandler` into a Connect (or Express) application, configuring it to only run in a development environment and providing a custom logging function that sends desktop notifications for errors."},"warnings":[{"fix":"If you rely on console logging in test environments, explicitly set `log: true` in the `errorhandler` options: `app.use(errorhandler({ log: true }))`.","message":"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.","severity":"breaking","affected_versions":">=1.5.0"},{"fix":"Always conditionally enable `errorhandler` based on `process.env.NODE_ENV`. For production, use a more generic error handling middleware that does not expose sensitive information, e.g., `app.use(function (err, req, res, next) { res.status(500).send('Something broke!'); })`.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"The `log` function should only be used for side-effects like logging to a file, database, or sending notifications. Any response modification must occur *before* the `errorhandler` middleware sends its response.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always pass actual `Error` objects to `next()` when signaling an error, e.g., `next(new Error('Description'))` or a custom error class extending `Error`. This provides better control over what information is presented.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure 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.","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.","error":"Error: Can't set headers after they are sent to the client"},{"fix":"Make 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();`.","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.","error":"TypeError: app.use is not a function"}],"ecosystem":"npm","meta_description":null}