📖 Scenario: You are building a simple Express server that responds to user requests. Sometimes, things can go wrong, like a missing page or a server problem. Proper error handling helps your server respond nicely instead of crashing or confusing users.
🎯 Goal: Build a basic Express server that includes error handling middleware to catch and respond to errors gracefully.
📋 What You'll Learn
Create an Express app with a route that triggers an error
Add a variable to hold the error message
Use error handling middleware to catch errors
Send a proper error response to the client
💡 Why This Matters
🌍 Real World
Error handling in Express is critical to keep web servers stable and provide clear feedback to users when something goes wrong.
💼 Career
Understanding error handling is essential for backend developers to build reliable and user-friendly web applications.
Progress0 / 4 steps
1
Set up Express app with a route that triggers an error
Create an Express app by requiring express and calling express(). Then create a route /error that throws an error with the message 'Something went wrong!'.
Express
Hint
Use app.get to create the route and call next() with an error.
2
Add a variable to hold the error message
Create a variable called errorMessage and set it to the string 'An unexpected error occurred.'.
Express
Hint
Just create a constant variable with the exact name and value.
3
Add error handling middleware
Add error handling middleware using app.use with four parameters: err, req, res, next. Inside, set the response status to 500 and send a JSON object with a key error and value errorMessage.
Express
Hint
Error handling middleware has four parameters and must be added after routes.
4
Start the server to complete the app
Add app.listen to start the server on port 3000 and add a callback that logs 'Server running on port 3000'.
Express
Hint
Use app.listen with port 3000 and a callback that logs the message.
Practice
(1/5)
1. Why is error handling important in an Express app?
easy
A. It automatically fixes bugs in the code.
B. It makes the app run faster by skipping checks.
C. It prevents the app from crashing and shows friendly messages to users.
D. It hides all errors so developers don't see them.
Solution
Step 1: Understand the role of error handling
Error handling helps catch problems before they crash the app and allows showing helpful messages.
Step 2: Compare options with this role
Only It prevents the app from crashing and shows friendly messages to users. describes preventing crashes and user-friendly messages, which is the main goal.
Final Answer:
It prevents the app from crashing and shows friendly messages to users. -> Option C