Error-handling middleware
Special middleware with four arguments that handles errors passed via next(err).
Syntax
app.use((err, req, res, next) => { ... }) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
err | any | Yes | The error forwarded from `next(err)` or a thrown/rejected handler. |
req | Request | Yes | The request object. |
res | Response | Yes | The response object. |
next | function | Yes | Pass to the next error handler, or default handler. |
Returns
void — Sends the error response.
Examples
app.get('/x', (req, res, next) => {
next(new Error('boom'));
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({ error: err.message });
});
Output
(500) {"error":"boom"}
// Express 5: rejected async handlers reach here automatically
app.get('/data', async (req, res) => {
const d = await mightThrow();
res.json(d);
});
app.use((err, req, res, next) => res.sendStatus(500));
Output
(500 Internal Server Error)
Notes
Identified solely by its four-argument signature, so keep the
unused `next`. Register it LAST, after all routes. In Express 5
rejected promises and thrown errors in async handlers are forwarded
automatically; in Express 4 you must call `next(err)` yourself.
Never leak stack traces to clients in production.