Consider an Express app with normal middleware and error-handling middleware. What happens when an error is passed to next()?
const express = require('express'); const app = express(); app.use((req, res, next) => { if (req.query.fail) { next(new Error('Failure triggered')); } else { next(); } }); app.use((req, res, next) => { res.send('Success'); }); app.use((err, req, res, next) => { res.status(500).send('Error caught: ' + err.message); });
Think about how Express decides which middleware to run when next() receives an error.
When next() is called with an error, Express skips normal middleware and runs error-handling middleware. This middleware has four arguments (err, req, res, next) and handles the error, often sending a 500 response.
Which option contains a syntax error in defining error-handling middleware in Express?
app.use(function(err, req, res) {
res.status(500).send('Error: ' + err.message);
});Error-handling middleware must have exactly four parameters.
Error-handling middleware in Express must have four parameters: err, req, res, next. Missing the next parameter causes Express to treat it as normal middleware, so it won't catch errors properly.
Given this Express app, why does the error-handling middleware never respond?
const express = require('express'); const app = express(); app.use((req, res, next) => { next(new Error('Oops')); }); app.use((req, res, next) => { res.send('Hello'); }); app.use((req, res, next, err) => { res.status(500).send('Error: ' + err.message); });
Check the order of parameters in error-handling middleware.
Error-handling middleware must have four parameters in this order: err, req, res, next. The code has req, res, next, err, so Express does not recognize it as error-handling middleware and never calls it.
Consider this Express async middleware that throws an error. What response does the client receive?
const express = require('express'); const app = express(); app.use(async (req, res, next) => { throw new Error('Async failure'); }); app.use((err, req, res, next) => { res.status(500).send('Caught: ' + err.message); });
Think about how Express handles errors thrown inside async functions.
Express does not automatically catch errors thrown inside async middleware unless next(err) is called or the async function is wrapped. Throwing an error inside async middleware causes an unhandled promise rejection and crashes the app.
Choose the correct statement about error-handling middleware behavior in Express.
Recall how Express detects error-handling middleware.
Express identifies error-handling middleware by the function signature having four parameters: err, req, res, next. This is how it knows to call it when an error occurs. Other statements are false: error handlers do not have to be last, next() without arguments inside error handlers passes control to normal middleware, and Express does not automatically send 500 responses without error handlers.