📖 Scenario: You are building a simple Express server that fetches user data asynchronously. You want to handle errors properly in your routes so the server does not crash and sends meaningful error messages to clients.
🎯 Goal: Create an Express route that fetches user data asynchronously and handles errors using async/await and try/catch blocks.
📋 What You'll Learn
Create an Express app with a route /user/:id
Use an async function to simulate fetching user data
Add a configuration variable for a delay time
Use try/catch inside the route to handle errors
Send a JSON response with user data or error message
💡 Why This Matters
🌍 Real World
Handling asynchronous operations and errors in web server routes is essential for building reliable APIs that do not crash and provide clear feedback to clients.
💼 Career
Backend developers frequently write async routes in Express and must handle errors properly to maintain server stability and good user experience.
Progress0 / 4 steps
1
Set up Express app and user data
Create a variable called express that requires the 'express' module. Then create an Express app by calling express() and assign it to a variable called app. Finally, create a constant object called users with these exact entries: 1: { name: 'Alice' }, 2: { name: 'Bob' }.
Express
Hint
Use require('express') to import Express. Create app by calling express(). Define users as an object with keys 1 and 2.
2
Add delay configuration variable
Create a constant called delay and set it to 1000 (milliseconds).
Express
Hint
Just create a constant delay and assign it the number 1000.
3
Create async function to fetch user data
Write an async function called getUserById that takes id as a parameter. Inside, return a new Promise that waits for delay milliseconds using setTimeout. After the delay, if users[id] exists, resolve with users[id], otherwise reject with an Error with message 'User not found'.
Express
Hint
Use new Promise with setTimeout to simulate delay. Resolve if user exists, reject with error if not.
4
Add async route with error handling
Add a GET route to app at path /user/:id. Use an async function with parameters req and res. Inside, use a try/catch block. In try, await getUserById(req.params.id) and send the user data as JSON with res.json(user). In catch, send a 404 status with JSON containing { error: error.message }.
Express
Hint
Use app.get with async function. Use try/catch to await getUserById. Send JSON response or error with status 404.
Practice
(1/5)
1. What is the main reason to use try/catch blocks inside async route handlers in Express?
easy
A. To automatically retry failed requests
B. To catch errors from asynchronous code and pass them to Express error handlers
C. To make the route handler run faster
D. To prevent the server from starting
Solution
Step 1: Understand async errors in Express routes
Async functions can throw errors that are not caught automatically by Express, so we need to catch them manually.
Step 2: Use try/catch to handle errors
Wrapping async code in try/catch allows catching errors and passing them to Express with next(error).
Final Answer:
To catch errors from asynchronous code and pass them to Express error handlers -> Option B
Quick Check:
try/catch in async routes = catch async errors [OK]
Hint: Use try/catch to catch async errors and call next(error) [OK]
What is the problem with this code regarding error handling?
medium
A. It sends response twice
B. It incorrectly uses next() inside the route
C. It lacks a try/catch block to handle errors from the async function
D. It uses synchronous code inside async function
Solution
Step 1: Check for error handling in async code
The async function getUser() might throw errors, but no try/catch is used.
Step 2: Understand Express error propagation
Without try/catch and calling next(error), errors will not be handled properly and may crash the server.
Final Answer:
It lacks a try/catch block to handle errors from the async function -> Option C
Quick Check:
Async routes need try/catch for error handling [OK]
Hint: Always wrap async code in try/catch to handle errors [OK]
Common Mistakes:
Omitting try/catch in async route handlers
Expecting Express to catch async errors automatically
Not calling next(error) inside catch
5. You want to create a centralized error handler middleware in Express that catches all errors passed by next(error). Which of the following is the correct way to define this middleware?
Error handlers must have four parameters: (err, req, res, next).
Step 2: Check each option for correct signature and response
app.use((err, req, res, next) => { res.status(500).json({ message: err.message }); }); uses all four parameters and sends JSON with error message and status 500, which is correct.