Bird
Raised Fist0
Node.jsframework~10 mins

Error response formatting in Node.js - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Error response formatting
Receive request
↓
Process request
↓
Error occurs?
No→Send success response
Yes↓
Format error response
↓
Send error response
↓
End
The server receives a request, processes it, checks for errors, formats an error response if needed, then sends it back.
Execution Sample
Node.js
app.get('/data', (req, res) => {
  try {
    throw new Error('Data not found');
  } catch (err) {
    res.status(404).json({ error: err.message });
  }
});
This code handles a GET request and sends a formatted JSON error response if an error occurs.
Execution Table
StepActionError Thrown?Response StatusResponse Body
1Request received at /dataNoN/AN/A
2Try block runsYes: 'Data not found'N/AN/A
3Catch block catches errorYes404N/A
4Format error responseYes404{"error":"Data not found"}
5Send error responseYes404{"error":"Data not found"}
💡 Error caught and formatted response sent with status 404
Variable Tracker
VariableStartAfter Step 2After Step 3Final
err.messageundefinedData not foundData not foundData not found
res.statusCode200 (default)200404404
response bodyemptyemptyempty{"error":"Data not found"}
Key Moments - 2 Insights
Why do we set the status code before sending the JSON response?
Because the status code tells the client what kind of response it is (error or success). The execution_table row 3 shows setting status 404 before sending the JSON body.
What happens if we don't catch the error?
The server might crash or send a generic error. The execution_table shows the catch block handling the error to send a clear message.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the response status code after step 3?
A404
B200
C500
DUndefined
💡 Hint
Check the 'Response Status' column at step 3 in the execution_table.
At which step is the error message added to the response body?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Response Body' column in the execution_table to see when the JSON error is formatted.
If the error message was 'User not found', how would the response body change at step 5?
A{"error":"Data not found"}
B{}
C{"error":"User not found"}
DNo response body
💡 Hint
Refer to variable_tracker for err.message and how it affects the response body.
Concept Snapshot
Error response formatting in Node.js:
- Catch errors in try-catch
- Set HTTP status code (e.g., 404)
- Send JSON with error message
- Helps clients understand what went wrong
- Always format errors before sending response
Full Transcript
When a Node.js server receives a request, it tries to process it. If an error happens, the catch block catches it. The server sets the HTTP status code to indicate an error, like 404 for not found. Then it sends a JSON response with an error message. This helps the client know what went wrong clearly. The execution table shows each step: receiving the request, error thrown, catching it, setting status, formatting JSON, and sending the response. Variables like err.message and res.statusCode change during these steps. Setting the status before sending the response is important so the client understands the error type. If errors are not caught, the server might crash or send unclear responses. Changing the error message updates the JSON sent back.

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

  1. Step 1: Understand HTTP status codes

    HTTP status codes tell the client if a request succeeded or failed.
  2. Step 2: Role of res.status()

    This method sets the HTTP status code in the response, indicating success or error.
  3. Final Answer:

    To set the HTTP status code for the response -> Option D
  4. 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

  1. Step 1: Check Express response methods

    Use res.status(code) to set status, then json() to send JSON.
  2. Step 2: Validate syntax correctness

    Only res.status(404).json({ error: 'Not found' }) is valid syntax.
  3. Final Answer:

    res.status(404).json({ error: 'Not found' }) -> Option B
  4. Quick Check:

    Set status then send JSON [OK]
Hint: Use res.status(code).json(object) for error responses [OK]
Common Mistakes:
  • Calling res.send() before json()
  • Passing status code inside json()
  • Using non-existent res.error() method
3. Given this Express error handler code:
app.use((err, req, res, next) => {
  res.status(500).json({
    message: err.message,
    code: 'SERVER_ERROR'
  });
});

What will the client receive if an error with message 'Database down' occurs?
medium
A. {"message":"Database down","code":"SERVER_ERROR"} with status 500
B. {"error":"Database down"} with status 200
C. Plain text 'Database down' with status 500
D. Empty response with status 500

Solution

  1. Step 1: Analyze the error handler response

    The handler sets status 500 and sends JSON with message and code fields.
  2. Step 2: Match error message and response

    The JSON includes the error message 'Database down' and code 'SERVER_ERROR'.
  3. Final Answer:

    {"message":"Database down","code":"SERVER_ERROR"} with status 500 -> Option A
  4. Quick Check:

    Error message and code sent as JSON with 500 status [OK]
Hint: Error handlers send JSON with message and code [OK]
Common Mistakes:
  • Assuming status 200 by default
  • Expecting plain text instead of JSON
  • Missing error code in response
4. Identify the error in this Express error response code:
app.use((err, req, res) => {
  res.status(400).json({ message: err.message });
});
medium
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

  1. Step 1: Check Express error middleware signature

    Error middleware must have four parameters: err, req, res, next.
  2. Step 2: Identify missing parameter

    The code has only three parameters, missing next, so Express won't recognize it as error handler.
  3. Final Answer:

    Missing the next parameter in the middleware function -> Option A
  4. 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?
hard
A. app.use((err, req, res, next) => { if (err.statusCode) { res.json({ code: err.statusCode, message: err.message }); } else { res.status(500).send('Error'); } });
B. app.use((err, req, res) => { res.status(err.statusCode).json({ message: err.message }); });
C. app.use((err, req, res, next) => { const status = err.statusCode || 500; const message = err.message || 'Internal Server Error'; res.status(status).json({ code: status, message }); });
D. app.use((err, req, res, next) => { res.status(500).json({ code: 'ERROR', message: 'Something went wrong' }); });

Solution

  1. Step 1: Check for error statusCode and message

    Use err.statusCode if present, else default to 500; similarly for message.
  2. Step 2: Send JSON response with status and message

    Set status with res.status(status) and send JSON with code and message fields.
  3. Final Answer:

    app.use((err, req, res, next) => { const status = err.statusCode || 500; const message = err.message || 'Internal Server Error'; res.status(status).json({ code: status, message }); }); -> Option C
  4. Quick Check:

    Use defaults and send JSON with status and message [OK]
Hint: Use || to default status and message in error handler [OK]
Common Mistakes:
  • Missing next parameter in middleware
  • Not defaulting status or message
  • Sending plain text instead of JSON
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard