Lesson 15 / 23
Error-Handling Middleware
A special 4-argument middleware Express recognizes automatically.
The 4-argument signature
A middleware with exactly (err, req, res, next) is treated as an error handler. Express skips straight to it whenever next(err) is called anywhere.
A centralized handler
Register it last, after all routes — one place to log errors and shape the JSON response.
app.get('/risky', (req, res, next) => {
try {
throw new Error('Something broke');
} catch (err) {
next(err); // hand off to the error handler
}
});
// must be registered after all routes
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: err.message || 'Internal Server Error' });
});Quick check: How many arguments must an error-handling middleware function accept?
- 2
- 3
- 4
Answer
4 — Express identifies error handlers purely by arity — exactly (err, req, res, next).