📖 Scenario: You are building a simple Node.js server that sends error responses in a consistent JSON format. This helps clients understand what went wrong.
🎯 Goal: Create a Node.js server that returns error responses with a JSON object containing status, message, and errorCode fields.
📋 What You'll Learn
Create an error object with specific properties
Add a configuration variable for default error code
Write a function to format the error response JSON
Send the formatted error response in the server
💡 Why This Matters
🌍 Real World
APIs and web servers need to send clear, consistent error messages so clients can handle problems properly.
💼 Career
Understanding error response formatting is essential for backend developers working with Node.js and building reliable web services.
Progress0 / 4 steps
1
Create the error object
Create a constant called error with these exact properties: status set to 400, message set to "Invalid input", and errorCode set to "INVALID_INPUT".
Create a constant called DEFAULT_ERROR_CODE and set it to the string "UNKNOWN_ERROR".
Node.js
Hint
Use const DEFAULT_ERROR_CODE = "UNKNOWN_ERROR"; to set the default error code.
3
Write the error formatting function
Write a function called formatErrorResponse that takes an error object as input and returns a new object with status, message, and errorCode. Use the errorCode from the input error if it exists; otherwise, use DEFAULT_ERROR_CODE.
Node.js
Hint
Use error.errorCode || DEFAULT_ERROR_CODE to provide a fallback error code.
4
Send the formatted error response in a Node.js server
Create a simple Node.js HTTP server using http.createServer. In the request handler, use formatErrorResponse(error) to get the error JSON, set the response header Content-Type to application/json, and send the JSON stringified error response with the status code from error.status.
Node.js
Hint
Use http.createServer and res.writeHead with Content-Type set to application/json.
Practice
(1/5)
1. What is the main purpose of using res.status() in Node.js error handling?
easy
A. To log errors on the server console
B. To send a success message to the client
C. To restart the server automatically
D. To set the HTTP status code for the response
Solution
Step 1: Understand HTTP status codes
HTTP status codes tell the client if a request succeeded or failed.
Step 2: Role of res.status()
This method sets the HTTP status code in the response, indicating success or error.
Final Answer:
To set the HTTP status code for the response -> Option D
Quick Check:
res.status() sets HTTP status code [OK]
Hint: Remember: status sets code, not message or logs [OK]
Common Mistakes:
Confusing status with sending messages
Thinking it logs errors
Assuming it restarts the server
2. Which of the following is the correct way to send a JSON error response with status 404 in Express?
easy
A. res.send(404).json({ error: 'Not found' })
B. res.status(404).json({ error: 'Not found' })
C. res.json(404, { error: 'Not found' })
D. res.error(404).send({ error: 'Not found' })
Solution
Step 1: Check Express response methods
Use res.status(code) to set status, then json() to send JSON.
Step 2: Validate syntax correctness
Only res.status(404).json({ error: 'Not found' }) is valid syntax.
Final Answer:
res.status(404).json({ error: 'Not found' }) -> Option B
Quick Check:
Set status then send JSON [OK]
Hint: Use res.status(code).json(object) for error responses [OK]
A. Missing the next parameter in the middleware function
B. Using res.status() instead of res.sendStatus()
C. Not calling res.end() after json()
D. Incorrect status code for errors
Solution
Step 1: Check Express error middleware signature
Error middleware must have four parameters: err, req, res, next.
Step 2: Identify missing parameter
The code has only three parameters, missing next, so Express won't recognize it as error handler.
Final Answer:
Missing the next parameter in the middleware function -> Option A
Quick Check:
Error middleware needs 4 params: err, req, res, next [OK]
Hint: Error middleware must have 4 parameters [OK]
Common Mistakes:
Leaving out next parameter
Confusing res.status() with res.sendStatus()
Thinking json() needs res.end()
5. You want to send a detailed error response with a custom code and message, but only if the error has a statusCode property. Otherwise, send a 500 status with a generic message. Which code snippet correctly implements this in Express?