NODEJS Contents

Error Middleware: One Place to Handle Failures

Error middleware is the reliability backbone: normalize failures into a stable response shape while preserving logs, stack traces, and root causes.

On this page

Why Error Middleware Exists

Production systems must not leak internals and must return consistent error responses. Error middleware is where you translate exceptions into a safe, observable HTTP contract.

Error Handler Must Be Last

Express only routes errors to middleware with four arguments: (err, req, res, next). It must be registered after routes.

import type { Request, Response, NextFunction } from 'express';

export function errorHandler(err: unknown, req: Request, res: Response, _next: NextFunction) {
  const requestId = (req as any).requestId as string | undefined;

  const status = 500;
  res.status(status).json({
    error: { code: 'INTERNAL_ERROR', message: 'Unexpected error', requestId }
  });
}

Production Rules

  • Always log the original error with context (route, requestId)
  • Return stable client-facing codes and messages
  • Do not expose stack traces in production responses