ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Node.js Tutorial• 8 min read

Middleware Architecture & Global Error Handling

The onion model, request logging, security headers, and centralized exception catching

Middleware functions have access to the request object (req), response object (res), and the next() middleware function in the application’s request-response cycle.

Understanding the Middleware Pipeline

Middleware can execute arbitrary code, make changes to req and res, end the request-response cycle, or call next() to invoke the next middleware.

If a middleware neither calls res.send() nor calls next(), the client request will be left hanging indefinitely.

Global error middleware has 4 arguments: (err, req, res, next). Express recognizes this specific signature as an error handler.

Custom Logger and Centralized Error Middleware
import express from 'express';

const app = express();

// Custom request duration logger middleware
app.use((req, res, next) => {
  const start = Date.now();
  res.on('finish', () => {
    const elapsed = Date.now() - start;
    console.log(`[${req.method}] ${req.url} -> ${res.statusCode} (${elapsed}ms)`);
  });
  next(); // Pass control to next handler
});

// Route that triggers an intentional error
app.get('/unstable-route', (req, res, next) => {
  try {
    throw new Error('Database connection timed out.');
  } catch (error) {
    next(error); // Forward error to error middleware
  }
});

// Centralized Error Handling Middleware (4 arguments)
app.use((err, req, res, next) => {
  console.error('Unhandled Application Error:', err.message);
  res.status(err.status || 500).json({
    success: false,
    error: {
      message: err.message || 'Internal Server Error',
      timestamp: new Date().toISOString()
    }
  });
});
Four arguments (err, req, res, next) inform Express that this function handles uncaught errors.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

How many parameters must an Express middleware function take for Express to recognize it as an error-handling middleware?