A centralized error handler helps catch and manage all errors in one place. This keeps your code clean and makes debugging easier.
Centralized error handler in Express
app.use((err, req, res, next) => {
// handle error here
res.status(500).send('Something broke!');
});This middleware has four parameters: err, req, res, and next. Express knows this is an error handler because it has four arguments.
Place this middleware after all other routes and middleware.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Internal Server Error');
});app.use((err, req, res, next) => {
if (err.type === 'database') {
res.status(503).send('Database error');
} else {
res.status(500).send('Server error');
}
});This Express app throws an error on the home route. The centralized error handler catches it, logs the message, and sends a friendly error response.
import express from 'express'; const app = express(); app.get('/', (req, res) => { throw new Error('Oops!'); }); // Centralized error handler app.use((err, req, res, next) => { console.error('Error caught:', err.message); res.status(500).send('Something went wrong!'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Always place the error handler after all other middleware and routes.
Use next(err) in your routes to pass errors to this handler.
Customize error responses for better user experience.
Centralized error handlers catch all errors in one place.
They keep your code clean and consistent.
Place them last in your middleware stack.
Practice
Solution
Step 1: Understand error handling in Express
Express allows middleware to catch errors and handle them centrally.Step 2: Identify the role of centralized error handler
It collects all errors from routes and middleware to respond consistently.Final Answer:
To catch and handle all errors in one place -> Option CQuick Check:
Centralized error handler = catch all errors [OK]
- Thinking it improves server speed
- Confusing with static file serving
- Mixing with session management
Solution
Step 1: Recall Express error handler signature
Error handlers have four parameters: (err, req, res, next).Step 2: Match the correct middleware signature
app.use((err, req, res, next) => { res.status(500).send(err.message); }); uses all four parameters correctly and sends error message.Final Answer:
app.use((err, req, res, next) => { res.status(500).send(err.message); }); -> Option BQuick Check:
Error handler middleware needs 4 params [OK]
- Using only 3 parameters in error handler
- Defining error handler as route handler
- Missing the 'err' parameter
app.get('/test', (req, res, next) => {
next(new Error('Oops!'));
});
app.use((err, req, res, next) => {
res.status(500).send('Error caught: ' + err.message);
});Solution
Step 1: Understand error propagation in route
The route calls next() with an Error object, triggering error middleware.Step 2: Check error handler response
The error handler sends status 500 and message including error text.Final Answer:
Status 500 with body 'Error caught: Oops!' -> Option AQuick Check:
Error passed to handler = 500 response with message [OK]
- Expecting status 200 instead of 500
- Thinking error handler is skipped
- Assuming server crashes on error
app.use((req, res, next) => {
throw new Error('Fail');
});
app.use((req, res, next) => {
res.status(500).send('Error occurred');
});Solution
Step 1: Check error handler signature
Error handlers must have 4 parameters: (err, req, res, next).Step 2: Analyze given error handler
The second middleware has only (req, res, next), so it won't catch errors.Final Answer:
Error handler middleware missing 'err' parameter -> Option AQuick Check:
Error handler needs 4 params to catch errors [OK]
- Forgetting the 'err' parameter in error handler
- Placing error handler before routes
- Thinking throwing error is disallowed
Solution
Step 1: Confirm error handler signature and logging
app.use((err, req, res, next) => { console.error(err); res.status(err.status || 500).json({ error: err.message }); }); uses (err, req, res, next) and logs error with console.error.Step 2: Check response format and status code
app.use((err, req, res, next) => { console.error(err); res.status(err.status || 500).json({ error: err.message }); }); sends JSON with error message and status code from error or 500.Final Answer:
app.use((err, req, res, next) => { console.error(err); res.status(err.status || 500).json({ error: err.message }); }); -> Option DQuick Check:
Proper error handler logs and sends JSON with status [OK]
- Missing 'next' parameter in error handler
- Not logging the error
- Sending plain text instead of JSON
Ready to prove it?
Pass the test and this pattern moves unknown
