Bird
0
0

You want to create a centralized error handler that logs errors and sends JSON responses with status and message. Which code snippet correctly implements this in Express?

hard📝 Application Q15 of 15
Node.js - Error Handling Patterns
You want to create a centralized error handler that logs errors and sends JSON responses with status and message. Which code snippet correctly implements this in Express?
Aapp.use((err, req, res, next) => { res.sendStatus(200); });
Bapp.use((req, res, next) => { console.error('Error occurred'); res.status(500).json({ error: 'Unknown error' }); });
Capp.use((err, req, res) => { console.log(err); res.send('Error happened'); });
Dapp.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: err.message }); });
Step-by-Step Solution
Solution:
  1. Step 1: Verify error middleware signature and logging

    The correct snippet uses four parameters (err, req, res, next) and logs the error stack with console.error(err.stack).
  2. Step 2: Check response format and status code

    It sends a JSON response with the error message and sets the status to err.status || 500.
  3. Step 3: Evaluate other options

    The other options lack the proper signature, correct logging, status handling, or JSON response.
  4. Final Answer:

    app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: err.message }); }); -> Option D
  5. Quick Check:

    Proper error middleware logs and sends JSON with status [OK]
Quick Trick: Error middleware: 4 params, log error, send JSON with status [OK]
Common Mistakes:
  • Missing 'next' parameter in middleware
  • Sending status 200 on error
  • Not sending JSON response format

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes