๐ Scenario: You are building a simple Express server that handles user requests. Sometimes errors happen, like when a user asks for a page that does not exist. To keep your server friendly and clear, you want to add a special error-handling middleware that catches errors and sends a nice message back to the user.
๐ฏ Goal: Create an Express app with a route that triggers an error, then add an error-handling middleware that catches the error and sends a JSON response with the error message and a 500 status code.
๐ What You'll Learn
Create an Express app instance called app
Add a route /cause-error that throws an error with message 'Something went wrong!'
Create an error-handling middleware function with four parameters: err, req, res, next
In the error handler, send a JSON response with status 500 and message from the error
Use app.use to add the error-handling middleware after the route
๐ก Why This Matters
๐ Real World
Error-handling middleware helps keep web servers stable and user-friendly by catching unexpected problems and sending clear messages.
๐ผ Career
Understanding error-handling middleware is essential for backend developers working with Express to build reliable and maintainable web applications.
Progress0 / 4 steps
1
Create the Express app and route
Write code to import Express, create an app instance called app, and add a GET route /cause-error that throws a new Error with the message 'Something went wrong!'.
Express
Hint
Use const app = express() to create the app. Then use app.get('/cause-error', (req, res) => { throw new Error('Something went wrong!') }) to add the route.
2
Create the error-handling middleware function
Write a function called errorHandler that takes four parameters: err, req, res, and next. Inside the function, send a JSON response with status code 500 and a message property set to err.message.
Express
Hint
The error handler must have four parameters. Use res.status(500).json({ message: err.message }) to send the error message.
3
Add the error-handling middleware to the app
Use app.use to add the errorHandler middleware to the Express app after the route definition.
Express
Hint
Use app.use(errorHandler) to add the error handler after all routes.
4
Start the Express server
Add code to start the Express server on port 3000 using app.listen. Inside the listen callback, log the message 'Server running on port 3000'.
Express
Hint
Use app.listen(3000, () => { console.log('Server running on port 3000') }) to start the server.
Practice
(1/5)
1. What is the main purpose of error-handling middleware in Express?
easy
A. To serve static files like images and CSS
B. To parse incoming JSON request bodies
C. To catch errors and prevent the server from crashing
D. To log every request made to the server
Solution
Step 1: Understand middleware roles
Middleware can serve many roles, but error-handling middleware specifically catches errors.
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 B
Quick Check:
Error middleware params order = err, req, res, next [OK]
Hint: Error middleware params start with err, not req [OK]
Common Mistakes:
Swapping err and req parameters
Placing error middleware before routes
Forgetting to call next() when needed
5. You want to create an error-handling middleware that logs the error message and then passes the error to the next middleware. Which of the following implementations is correct?
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);
next(err);
});
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.