📖 Scenario: You are building a simple Express server that handles user requests. When something goes wrong, you want to send back a clear and consistent error message in JSON format.
🎯 Goal: Create an Express server that sends error responses with a JSON object containing error and message fields.
📋 What You'll Learn
Create an Express app instance
Add a route /user that triggers an error
Create a configuration variable errorMessage with the text 'User not found'
Use Express error handling middleware to send a JSON error response with error and message
Ensure the error response has HTTP status code 404
💡 Why This Matters
🌍 Real World
Web servers often need to send clear error messages in JSON format so client apps can handle errors gracefully.
💼 Career
Knowing how to format error responses in Express is essential for backend developers building APIs.
Progress0 / 4 steps
1
Setup Express app and route
Create an Express app by requiring express and calling express(). Then add a GET route /user that calls next(new Error('User not found')) to simulate an error.
Express
Hint
Remember to require Express and create the app instance first. Then add a GET route for '/user' that triggers an error using next(new Error('User not found')).
2
Add error message configuration
Create a constant variable called errorMessage and set it to the string 'User not found'.
Express
Hint
Define a constant named errorMessage and assign it the exact string 'User not found'.
3
Add error handling middleware
Add an Express error handling middleware function with four parameters: err, req, res, and next. Inside it, set the response status to 404 and send a JSON object with keys error set to true and message set to the errorMessage variable.
Express
Hint
Use app.use with four parameters to create error middleware. Set status 404 and respond with JSON containing error: true and message: errorMessage.
4
Start the Express server
Add code to start the Express server by calling app.listen on port 3000.
Express
Hint
Call app.listen with port 3000 to start the server.
Practice
(1/5)
1. What is the main purpose of using res.status() in Express error handling?
easy
A. To redirect the user to an error page
B. To send the error message as plain text
C. To set the HTTP status code of the response
D. To log the error on the server console
Solution
Step 1: Understand the role of res.status()
This method sets the HTTP status code that tells the client what kind of response it is (success, error, etc.).
Step 2: Differentiate from other response methods
Unlike sending messages or logging, res.status() only sets the status code, which is essential for error handling.
Final Answer:
To set the HTTP status code of the response -> Option C
Quick Check:
res.status() sets status code [OK]
Hint: Remember: status() sets code, json() sends data [OK]
Common Mistakes:
Confusing status() with sending the error message
Using status() to log errors instead of setting code
Thinking status() redirects the user
2. Which of the following is the correct way to send a JSON error response with status 404 in Express?
easy
A. res.json(404).send({ error: 'Not found' })
B. res.sendStatus(404).json({ error: 'Not found' })
C. res.status(404).send('Not found')
D. res.status(404).json({ error: 'Not found' })
Solution
Step 1: Identify correct chaining of methods
In Express, res.status(code) sets the status, and res.json(object) sends JSON data.
Step 2: Check each option's syntax
res.status(404).json({ error: 'Not found' }) correctly chains status(404) and json({ error: 'Not found' }). Others misuse method order or types.
Final Answer:
res.status(404).json({ error: 'Not found' }) -> Option D
Quick Check:
Use status() then json() [OK]
Hint: Set status first, then send JSON with json() [OK]
Common Mistakes:
Calling json() before status()
Using sendStatus() then json() which is invalid
Sending plain text instead of JSON for errors
3. What will be the HTTP status code and JSON response body when this Express code runs?
A. The status code is set after sending the response
B. The error message should not be sent in JSON
C. The middleware is missing the next() call
D. The error handler should not have four parameters
Solution
Step 1: Check order of response methods
Calling res.json() sends the response immediately. Setting status after sending has no effect.
Step 2: Correct order for setting status and sending response
Status must be set before sending JSON: res.status(500).json(...).
Final Answer:
The status code is set after sending the response -> Option A
Quick Check:
Status before sending response [OK]
Hint: Always set status before sending response [OK]
Common Mistakes:
Setting status after res.json()
Not sending status at all
Misunderstanding middleware parameters
5. You want to send a 422 Unprocessable Entity error with a JSON body containing { error: 'Invalid input', fields: ['name', 'email'] }. Which Express code snippet correctly formats this error response?
hard
A. res.json({ error: 'Invalid input', fields: ['name', 'email'] }).status(422);
B. res.status(422).json({ error: 'Invalid input', fields: ['name', 'email'] });
C. res.sendStatus(422).json({ error: 'Invalid input', fields: ['name', 'email'] });
D. res.status(400).json({ error: 'Invalid input', fields: ['name', 'email'] });
Solution
Step 1: Choose the correct status code and method order
Use res.status(422) to set the correct HTTP status code before sending JSON.
Step 2: Verify the JSON body matches the required error format
The JSON object includes both error and fields keys as specified.