Bird
0
0

You need a centralized error handler in Express that logs errors and sends a JSON response with the error status and message. Which implementation correctly achieves this?

hard📝 Application Q8 of 15
Node.js - Error Handling Patterns
You need a centralized error handler in Express that logs errors and sends a JSON response with the error status and message. Which implementation correctly achieves this?
Aapp.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ status: err.status || 500, message: err.message }); });
Bapp.use((err, req, res) => { console.log(err); res.json({ error: err.message }); });
Capp.use((req, res, next) => { if (res.error) { res.status(500).json({ error: 'Server error' }); } else { next(); } });
Dapp.use((err, req, res, next) => { res.status(200).json({ error: err.message }); });
Step-by-Step Solution
Solution:
  1. Step 1: Verify middleware signature

    app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ status: err.status || 500, message: err.message }); }); and D have correct four parameters; B misses 'next', C is not error middleware.
  2. Step 2: Check logging

    app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ status: err.status || 500, message: err.message }); }); logs error stack properly; B logs but misses 'next'; others don't log.
  3. Step 3: Check response status and format

    app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ status: err.status || 500, message: err.message }); }); sends status from error or 500 and JSON with status and message.
  4. Step 4: Identify incorrect responses

    D sends status 200 on error, which is incorrect; B misses status code; C is not error middleware.
  5. Final Answer:

    Option A correctly logs and sends JSON with status and message. -> Option A
  6. Quick Check:

    Correct signature, logging, and proper status code needed [OK]
Quick Trick: Use 4 params, log error, send JSON with status and message [OK]
Common Mistakes:
  • Sending HTTP 200 on error
  • Missing 'next' parameter
  • Not logging errors
  • Incorrect middleware signature

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes