0
0
Expressframework~20 mins

Error response formatting in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Error Response Formatting in Express
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Call app.listen with port 3000 to start the server.