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?
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.
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.
Step 4: Identify incorrect responses
D sends status 200 on error, which is incorrect; B misses status code; C is not error middleware.
Final Answer:
Option A correctly logs and sends JSON with status and message. -> Option A
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
Master "Error Handling Patterns" in Node.js
9 interactive learning modes - each teaches the same concept differently