or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-errorhandler

Development-only error handler middleware for Express.js applications with comprehensive error formatting and content negotiation.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/errorhandler@1.5.x

To install, run

npx @tessl/cli install tessl/npm-errorhandler@1.5.0

index.mddocs/

Error Handler

Error Handler is a development-only Express.js/Connect middleware that provides comprehensive error handling with content negotiation support. It displays detailed error information with full stack traces and object details, making it an essential debugging tool for Express.js applications during development.

Package Information

  • Package Name: errorhandler
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install errorhandler

Core Imports

const errorHandler = require("errorhandler");

For ES modules:

import errorHandler from "errorhandler";

Basic Usage

const express = require("express");
const errorHandler = require("errorhandler");

const app = express();

// Only use errorhandler in development
if (process.env.NODE_ENV === "development") {
  app.use(errorHandler());
}

// Example route that might throw an error
app.get("/error", (req, res, next) => {
  const err = new Error("Something went wrong!");
  err.status = 500;
  next(err);
});

app.listen(3000);

Capabilities

Error Handler Middleware Factory

Creates Express/Connect error handling middleware that provides comprehensive error reporting with content negotiation.

/**
 * Creates error handling middleware for Express/Connect applications
 * @param {Object} [options] - Configuration options
 * @param {boolean|Function} [options.log] - Logging configuration
 * @returns {Function} Express/Connect error middleware with signature (err, req, res, next) => void
 */
function errorHandler(options);

Parameters:

  • options (Object, optional): Configuration options
    • options.log (Boolean|Function, optional): Controls error logging behavior
      • true (default in non-test environments): Log errors to console.error
      • false: Disable error logging
      • Function: Custom log handler with signature (err, str, req, res) => void

Returns: Function - Express/Connect middleware that handles errors

Usage Examples:

// Basic usage with default logging
app.use(errorHandler());

// Disable logging
app.use(errorHandler({ log: false }));

// Custom logging function
app.use(errorHandler({
  log: (err, str, req, res) => {
    console.log(`Custom log: ${str}`);
  }
}));

Error Handler Title Property

Customizable template title for HTML error pages.

/**
 * Template title for HTML error pages
 * @type {string}
 * @default "Connect"
 */
errorHandler.title;

Usage Example:

const errorHandler = require("errorhandler");

// Customize the title shown in HTML error pages
errorHandler.title = "My App Development";

app.use(errorHandler());

Content Negotiation

The middleware automatically detects the client's preferred content type via the Accept header and responds accordingly:

HTML Response (text/html)

Returns a formatted HTML page with:

  • Error message and status code
  • Complete stack trace in a styled format
  • Built-in CSS styling for readability
  • Security headers to prevent content sniffing

JSON Response (application/json)

Returns a JSON object containing:

  • error.message: The error message
  • error.stack: The full stack trace
  • All enumerable properties from the error object

Example JSON Response:

{
  "error": {
    "message": "Something went wrong!",
    "stack": "Error: Something went wrong!\n    at /app/routes.js:10:15\n    at ...",
    "status": 500
  }
}

Plain Text Response (default)

Returns the error as plain text:

  • For Error objects: Uses the stack property
  • For non-Error objects: Uses util.inspect() output
  • For objects with custom toString(): Uses the custom method

Error Processing

Status Code Handling

The middleware respects error status codes in the following priority:

  1. err.status (preferred)
  2. err.statusCode (fallback)
  3. 500 (default for errors)

Error Value Types

The middleware handles different error types:

  • Error objects: Displays full stack trace
  • String errors: Shows the string value
  • Number errors: Converts to string representation
  • Object errors: Uses util.inspect() for detailed output
  • Objects with custom toString(): Uses the custom toString() method

Security Features

The middleware includes built-in security measures:

  • Sets X-Content-Type-Options: nosniff header to prevent MIME sniffing attacks
  • Handles already-sent responses by destroying the socket connection
  • Designed specifically for development environments only

Environment Integration

The middleware automatically adapts to different environments:

  • Development: Enables logging by default
  • Test: Disables logging by default
  • Production: Should not be used (development-only middleware)

Important: This middleware should never be used in production environments as it exposes sensitive application details including stack traces and internal application structure.

Types

/**
 * Configuration options for the error handler
 */
interface ErrorHandlerOptions {
  /** Controls error logging behavior */
  log?: boolean | ((err: Error, str: string, req: Request, res: Response) => void);
}

/**
 * Express/Connect error handling middleware signature
 */
interface ErrorMiddleware {
  (err: Error, req: Request, res: Response, next: NextFunction): void;
}