Which statement best describes the behavior?
In Express, error-handling middleware is defined with four parameters: (err, req, res, next). It catches errors passed to next(err) or thrown synchronously in routes or middleware. It does not run for every request, only when an error occurs.
Error-handling middleware in Express must have exactly four parameters: (err, req, res, next). This signature tells Express to treat it as error-handling middleware.
app.get('/test', (req, res) => { throw new Error('fail'); });
app.use((req, res, next) => { res.status(404).send('Not found'); });
app.use((err, req, res, next) => { res.status(500).send('Server error'); });Why does the error-handling middleware not catch the thrown error?
The 404 middleware catches all requests not handled by previous routes but does not pass errors to next(err). Since it is placed before the error-handling middleware and does not forward errors, the error-handling middleware never runs.
app.get('/fail', (req, res, next) => { next(new Error('fail')); });
app.use((err, req, res, next) => { res.status(400).send('Bad request'); });What status code will the client receive when requesting /fail?
The error-handling middleware sets the response status to 400 before sending the response. So the client receives status 400.
Express runs error-handling middleware in the order they are defined. Each can handle the error or pass it on by calling next(err). This allows chaining multiple error handlers.