Skip to main content
Intermediate Practical Programming Example 10 min read Node.js 22 LTS + Express + TypeScript

Express.js Middleware & Centralized Error Handling Pattern

Structure Express middleware pipelines predictably, wrap async handlers cleanly, and return structured JSON errors without leaking stack traces.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last updated: Verification Policy

Learning Objectives

  • Order Express request logging, JSON body parsing, route matching, 404 fallback, and error middleware cleanly.
  • Build an explicit `AppError` hierarchy distinguishing client 4xx validation errors from unexpected 5xx crashes.

Prerequisites

  • Node.js ESM/CJS basics and JavaScript Promises

How Express Pipeline Order Governs Reliability

Every Express middleware receives (req, res, next) sequentially in registration order. Registering your notFoundHandler after all routes and your 4-argument errorHandler(err, req, res, next) strictly last ensures unhandled rejections never crash your API or leak raw stack traces to browsers.

Explore database optimization in SQL Indexing or master backend Node.js deeply inside the Node.js Backend Career Program.

Practical Programming Examples

Typed AppError + Centralized 4-Argument Express Error Handler

Standardize client 4xx vs unexpected 500 JSON responses cleanly inside Express.

Node.js 22 LTS + Express 4
import express from 'express';

class AppError extends Error {
  constructor(message, statusCode = 500) {
    super(message);
    this.statusCode = statusCode;
  }
}

const asyncWrap = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);

const app = express();
app.use(express.json({ limit: '100kb' }));

app.get('/api/courses/:code', asyncWrap(async (req, res) => {
  if (req.params.code !== 'NBCP') throw new AppError('Course code not found', 404);
  res.json({ code: 'NBCP', durationMonths: 6 });
}));

app.use((err, req, res, _next) => {
  const status = err.statusCode || 500;
  res.status(status).json({ error: status >= 500 ? 'Internal server error' : err.message });
});
Expected Output
GET /api/courses/UNKNOWN -> HTTP 404 {"error":"Course code not found"}
Step-by-Step Execution
  1. `asyncWrap` forwards rejected async route promises automatically into Express `next(err)`.
  2. The 4-parameter `(err, req, res, _next)` middleware suppresses raw internal details on 5xx faults.

Common Mistakes to Avoid

  • Omitting `_next` in `app.use((err, req, res) => ...)` — Express treats 3-arg functions as regular middleware and skips them.
  • Registering error middleware BEFORE routes are mounted.

Production Best Practices

  • Bound `express.json({ limit: "100kb" })` to block oversized payload DoS vectors.
  • Handle `SIGTERM` gracefully by draining HTTP connections and PostgreSQL/Redis pools.

Technical Interview Relevance

Key backend Node.js question checking Express 4-argument signatures, async error propagation, and graceful shutdowns.

Practice & Self-Check Questions

Why should JSON APIs return generic error messages on HTTP 500 instead of forwarding `err.stack`?

Stack traces leak file paths, dependency versions, and SQL structure to attackers; log full context server-side with a request ID and return a generic safe message publicly.

Optional Next Step

Have Questions About Learning Node.js Structured Cohorts?

Request the NBCP syllabus & weekend batch schedule from an Academic Counselor.

View NBCP Details →
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.