Consider a Node.js app with many routes and asynchronous operations. What is the main benefit of using centralized error handling middleware?
Think about how many places you would need to write error handling code without centralization.
Centralized error handling middleware in Node.js collects errors from different parts of the app and processes them in one place. This reduces repeated code and makes maintenance easier.
Given this Express error middleware, what will the client receive if an error with message 'File not found' is passed?
app.use((err, req, res, next) => {
res.status(404).json({ error: err.message });
});Look at the JSON key used in the response.
The middleware sends a JSON response with key 'error' and the error message. The status code is set to 404.
Which option contains the correct syntax for an Express centralized error handler?
app.use((err, req, res, next) => {
res.status(500).send('Server error');
});Check the number and order of parameters in the middleware function.
Express error middleware must have exactly four parameters: (err, req, res, next). Option A correctly follows this pattern.
Consider this Express route and error handler. Why does the error handler not catch the thrown error?
app.get('/data', async (req, res) => { throw new Error('Async failure'); }); app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });
Think about how Express handles errors in async functions.
Express does not automatically catch errors thrown in async functions. You must use try-catch or a wrapper to pass errors to next().
Given these middleware functions, what will be the final response sent to the client?
app.use((req, res, next) => {
next(new Error('First error'));
});
app.use((err, req, res, next) => {
if (err.message === 'First error') {
next(new Error('Second error'));
} else {
res.status(500).send(err.message);
}
});
app.use((err, req, res, next) => {
res.status(500).send(err.message);
});Follow the error passed through next() calls step by step.
The first middleware passes 'First error' to the error handler. The first error handler detects it and passes 'Second error' to the next error handler, which sends it as the response.