📖 Scenario: You are building a simple Express server that handles user requests. To keep your code clean and easy to maintain, you want to create a centralized error handler that catches all errors in one place and sends a friendly error message to the client.
🎯 Goal: Build an Express server with a centralized error handler middleware that catches errors from routes and sends a JSON response with the error message and status code.
📋 What You'll Learn
Create an Express app with a basic route that throws an error
Add a configuration variable for the default error status code
Implement a centralized error handler middleware function
Use the error handler middleware in the Express app
💡 Why This Matters
🌍 Real World
Centralized error handling is used in real web servers to keep code clean and provide consistent error messages to users.
💼 Career
Knowing how to implement error handling middleware is essential for backend developers working with Express or similar frameworks.
Progress0 / 4 steps
1
Create Express app with a route that throws an error
Create an Express app by requiring express and calling express(). Then create a route GET / that throws an error with the message 'Something went wrong!'.
Express
Hint
Use require('express') to import Express and express() to create the app. Define a route with app.get('/', (req, res) => { ... }) and throw an error inside it.
2
Add a default error status code variable
Create a constant variable called DEFAULT_ERROR_STATUS and set it to 500 to represent the default HTTP status code for server errors.
Express
Hint
Use const DEFAULT_ERROR_STATUS = 500; to set the default error status code.
3
Implement centralized error handler middleware
Create an error handler middleware function called errorHandler that takes four parameters: err, req, res, and next. Inside it, send a JSON response with status set to err.status || DEFAULT_ERROR_STATUS and message set to err.message.
Express
Hint
The error handler middleware has four parameters. Use res.status(...).json(...) to send the error status and message as JSON.
4
Use the error handler middleware in the Express app
Add the errorHandler middleware to the Express app using app.use(errorHandler) after all routes.
Express
Hint
Use app.use(errorHandler) after all routes to catch errors.
Practice
(1/5)
1. What is the main purpose of a centralized error handler in an Express app?
easy
A. To serve static files efficiently
B. To speed up the server response time
C. To catch and handle all errors in one place
D. To manage user sessions
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 C
Quick Check:
Centralized error handler = catch all errors [OK]
Hint: Centralized error handler catches errors globally, not locally [OK]
Common Mistakes:
Thinking it improves server speed
Confusing with static file serving
Mixing with session management
2. Which of the following is the correct way to define a centralized error handler middleware in Express?
easy
A. app.use((req, res) => { res.status(500).send('Error'); });
B. app.use((err, req, res, next) => { res.status(500).send(err.message); });
C. app.get('/error', (err, req, res) => { res.send('Error'); });
D. app.use((req, res, next) => { res.send('Error'); });
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.
A. Error handler middleware missing 'err' parameter
B. Throwing error inside middleware is not allowed
C. Error handler middleware should be placed before routes
D. Middleware order is correct, no error
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 A
Quick Check:
Error handler needs 4 params to catch errors [OK]
Hint: Error handler must have 4 parameters to work [OK]
Common Mistakes:
Forgetting the 'err' parameter in error handler
Placing error handler before routes
Thinking throwing error is disallowed
5. You want to create a centralized error handler that logs errors and sends a JSON response with status code and message. Which code snippet correctly implements this?