const express = require('express'); const app = express(); app.get('/test', (req, res, next) => { throw new Error('Oops!'); }); app.use((err, req, res, next) => { res.status(500).json({ message: err.message }); });
When an error is thrown inside a route, Express passes it to the error-handling middleware. Here, the middleware sends a JSON response with the error message and status 500.
Express recognizes error-handling middleware by the presence of four parameters. Option A correctly uses (err, req, res, next).
app.get('/async', async (req, res, next) => { throw new Error('Async error'); }); app.use((err, req, res, next) => { res.status(500).json({ error: err.message }); });
Errors thrown inside async route handlers are not automatically caught by Express. They must be passed to next(err) or handled with try/catch to reach the error middleware.
app.get('/fail', (req, res, next) => { next(new Error('Fail')); }); app.use((err, req, res, next) => { res.status(400).json({ message: err.message }); });
The error handler sets status 400 and sends the error message as JSON, so the client receives status 400 with the message.
Express processes middleware and routes in the order they are added. Error handlers must be last to catch errors from all previous middleware and routes.
