Error-handling middleware helps catch and respond to errors in your app. It keeps your app from crashing and shows friendly messages.
Error-handling middleware in Express
app.use(function (err, req, res, next) {
// handle the error here
});Error-handling middleware always has four parameters: err, req, res, and next.
It must be added after all other app.use() and routes.
app.use(function (err, req, res, next) {
res.status(500).send('Something broke!');
});app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).json({ error: err.message });
});This app throws an error when you visit the home page. The error-handling middleware catches it, logs it, and sends a custom message to the browser.
import express from 'express'; const app = express(); app.get('/', (req, res) => { throw new Error('Oops!'); }); // Error-handling middleware app.use((err, req, res, next) => { console.error('Error caught:', err.message); res.status(500).send('Custom error: ' + err.message); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always place error-handling middleware last, after all routes.
Use next(err) in routes or middleware to pass errors to this handler.
Sending detailed error info to users is okay in development but avoid it in production for security.
Error-handling middleware catches errors and prevents crashes.
It has four parameters: err, req, res, next.
Place it after all other middleware and routes.
Practice
Solution
Step 1: Understand middleware roles
Middleware can serve many roles, but error-handling middleware specifically catches errors.Step 2: Identify error-handling middleware purpose
Error-handling middleware prevents the server from crashing by catching errors and responding properly.Final Answer:
To catch errors and prevent the server from crashing -> Option CQuick Check:
Error-handling middleware = catch errors [OK]
- Confusing error middleware with static file serving
- Thinking it parses request bodies
- Assuming it logs requests
Solution
Step 1: Recall error middleware parameters
Error-handling middleware always has four parameters: err, req, res, next.Step 2: Match the correct parameter order
Only (err, req, res, next) has all four parameters in the correct order.Final Answer:
(err, req, res, next) -> Option AQuick Check:
Error middleware signature = (err, req, res, next) [OK]
- Using only three parameters
- Omitting the err parameter
- Wrong parameter order
const express = require('express');
const app = express();
app.get('/', (req, res) => {
throw new Error('Oops!');
});
app.use((err, req, res, next) => {
res.status(500).send('Error caught: ' + err.message);
});
app.listen(3000);Solution
Step 1: Identify error thrown in route
The route throws an error with message 'Oops!'.Step 2: Check error-handling middleware response
The error middleware catches the error and sends a 500 status with message including 'Oops!'.Final Answer:
The client receives 'Error caught: Oops!' with status 500 -> Option AQuick Check:
Error thrown = caught and sent with 500 [OK]
- Expecting server crash on error
- Confusing 404 with error response
- Missing error message in response
app.use((req, res, next, err) => {
res.status(500).send('Error: ' + err.message);
});Solution
Step 1: Check parameter order for error middleware
Error middleware must have parameters in order: err, req, res, next.Step 2: Identify incorrect order in code
The code has (req, res, next, err) which is incorrect.Final Answer:
The parameters are in the wrong order -> Option BQuick Check:
Error middleware params order = err, req, res, next [OK]
- Swapping err and req parameters
- Placing error middleware before routes
- Forgetting to call next() when needed
A) app.use((err, req, res, next) => {
console.log(err.message);
next(err);
});
B) app.use((req, res, next, err) => {
console.log(err.message);
next();
});
C) app.use((err, req, res) => {
console.log(err.message);
next(err);
});
D) app.use((err, req, res, next) => {
console.log(err.message);
res.send('Error logged');
});Solution
Step 1: Recall requirements for error-handling middleware that chains
It must have four parameters starting with err, log err.message, and call next(err) to pass the error to the next handler.Step 2: Match against provided implementations
Implementations with incorrect parameter order or count fail to receive or handle err properly; those that respond instead of calling next(err) break the chain.Final Answer:
app.use((err, req, res, next) => {
console.log(err.message);
next(err);
}); -> Option DQuick Check:
4 params + next(err) = correct chaining [OK]
- Wrong parameter order
- Forgetting next parameter
- Not calling next(err) to pass error along
- Sending response too early
Ready to prove it?
Pass the test and this pattern moves unknown
