Set your Publisher ID in src/config/ads.ts to display live ads.
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.
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()
}
});
});Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
How many parameters must an Express middleware function take for Express to recognize it as an error-handling middleware?