Centralized error handling helps catch and manage errors in one place. This keeps your code clean and easier to fix problems.
Centralized error handling in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
function errorHandler(err, req, res, next) {
res.status(500).send({ error: err.message });
}
app.use(errorHandler);This is an Express.js error middleware function with four parameters.
It must be added after all other routes and middleware.
Examples
Node.js
function errorHandler(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
}
app.use(errorHandler);Node.js
function errorHandler(err, req, res, next) {
res.status(err.status || 500).json({
message: err.message,
error: process.env.NODE_ENV === 'development' ? err : {}
});
}
app.use(errorHandler);Sample Program
This Express app throws an error on the home route. The centralized error handler catches it, logs it, and sends a JSON error message to the client.
Node.js
import express from 'express'; const app = express(); app.get('/', (req, res) => { throw new Error('Oops!'); }); function errorHandler(err, req, res, next) { console.error('Error caught:', err.message); res.status(500).send({ error: err.message }); } app.use(errorHandler); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Important Notes
Always place the error handler after all routes and middleware.
Use next(err) in async code to pass errors to the handler.
Customize error responses for better user experience.
Summary
Centralized error handling keeps error code in one place.
It improves app stability and debugging.
In Express, use a middleware with four parameters for errors.
Practice
1. What is the main benefit of centralized error handling in a Node.js Express app?
easy
Solution
Step 1: Understand centralized error handling purpose
Centralized error handling means managing errors in one place instead of scattering code everywhere.Step 2: Identify benefits of centralized error handling
This approach makes the app easier to maintain and debug because all error logic is together.Final Answer:
It keeps all error handling code in one place for easier maintenance. -> Option AQuick Check:
Centralized error handling = easier maintenance [OK]
Hint: Centralized means one place for all errors [OK]
Common Mistakes:
- Thinking it prevents errors automatically
- Believing it makes the app faster by skipping errors
- Confusing centralized handling with error fixing
2. Which of the following is the correct signature for an Express centralized error handling middleware?
easy
Solution
Step 1: Recall Express error middleware signature
Express error middleware must have four parameters: error, request, response, next.Step 2: Match the correct function signature
Only the function with (err, req, res, next) matches the required signature.Final Answer:
function errorHandler(err, req, res, next) { ... } -> Option BQuick Check:
Error middleware = 4 params (err, req, res, next) [OK]
Hint: Error middleware always has 4 parameters [OK]
Common Mistakes:
- Using 3 parameters instead of 4
- Omitting the error parameter
- Confusing normal middleware with error middleware
3. Given this Express app code snippet, what will be the response when a GET request to '/' throws an error?
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);medium
Solution
Step 1: Identify error throwing in route
The GET '/' route throws an error with message 'Oops!'.Step 2: Check error middleware handling
The error middleware catches the error and sends a 500 status with message 'Error caught: Oops!'.Final Answer:
The client receives 'Error caught: Oops!' with status 500. -> Option CQuick Check:
Thrown error caught by middleware = 500 response [OK]
Hint: Thrown errors go to error middleware response [OK]
Common Mistakes:
- Assuming server crashes on thrown error
- Expecting status 404 instead of 500
- Thinking error message is sent without prefix
4. What is wrong with this Express error handling middleware?
app.use((err, req, res) => {
res.status(500).send('Error: ' + err.message);
});medium
Solution
Step 1: Check middleware parameters
Express error middleware requires four parameters: err, req, res, next.Step 2: Identify missing parameter
This middleware has only three parameters, missing 'next', so Express treats it as normal middleware, not error handler.Final Answer:
It is missing the 'next' parameter, so Express won't recognize it as error middleware. -> Option AQuick Check:
Error middleware must have 4 params (err, req, res, next) [OK]
Hint: Error middleware always needs 4 parameters [OK]
Common Mistakes:
- Thinking parameter names must be specific
- Believing status code usage is wrong
- Placing middleware order incorrectly
5. You want to create a centralized error handler that logs errors and sends JSON responses with status and message. Which code snippet correctly implements this in Express?
hard
Solution
Step 1: Verify error middleware signature and logging
The correct snippet uses four parameters (err, req, res, next) and logs the error stack with console.error(err.stack).Step 2: Check response format and status code
It sends a JSON response with the error message and sets the status to err.status || 500.Step 3: Evaluate other options
The other options lack the proper signature, correct logging, status handling, or JSON response.Final Answer:
app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: err.message }); }); -> Option DQuick Check:
Proper error middleware logs and sends JSON with status [OK]
Hint: Error middleware: 4 params, log error, send JSON with status [OK]
Common Mistakes:
- Missing 'next' parameter in middleware
- Sending status 200 on error
- Not sending JSON response format
