In an Express 5 checkout route, which failures reach error middleware by themselves, and which still need an explicit next(err)?
answer
- what the router can observe
- returned promises are watched
- callbacks report errors as arguments
- un-returned chains float free
- timers run on a fresh stack
basics
~20 sIn Express 5, synchronous throws, async-function throws and rejections of a returned promise reach error middleware automatically. Callback errors, un-returned promise chains and timer callbacks do not: pass them to next(err), or the request hangs or the process crashes.
solid answer
~40 sExpress 5's router calls each handler inside a `try/catch` and, when the handler returns a promise, attaches a rejection handler that calls `next(err)`, using `new Error('Rejected promise')` when the reason is falsy. That covers a synchronous `throw`, an `async` handler whose `await` on a database call rejects, and a returned `.then()` chain. It cannot see anything outside that call or that promise. An error-first callback such as `fs.readFile`'s receives `err` as an argument, so you call `next(err)`; a `throw` inside that callback, an un-returned chain without `.catch(next)`, or a throw inside `setTimeout` escapes Express entirely and, under Node's defaults, crashes the process. Express 4 ignored returned promises, which is why code from that era ends chains with `.catch(next)` or wraps every async handler.
code
javascript · 29 linesconst express = require('express');
const fs = require('node:fs');
const app = express();
// Stand-in for a database client whose query rejects.
const db = {
findCart: async (id) => {
throw new Error(`cart ${id} unavailable`);
},
};
app.post('/checkout/:cartId', async (req, res) => {
const cart = await db.findCart(req.params.cartId); // Express 5 forwards this rejection
res.status(201).json({ cartId: cart.id });
});
app.get('/checkout/:cartId/receipt', (req, res, next) => {
fs.readFile('/srv/receipts/template.html', 'utf8', (err, html) => {
if (err) return next(err); // callback errors arrive as arguments, never as throws
res.type('html').send(html);
});
});
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
res.status(500).json({ message: 'Checkout failed' });
});
app.listen(3000);go deeper
Recall that Express 5 forwards throws and rejections from async handlers, while errors from callbacks must be passed to next(err) by hand.
Explain the mechanism: the router's try/catch plus a rejection handler on the returned promise, and why callbacks, floating chains and timers fall outside both.
Map each escape to its production symptom: a missed next(err) hangs one request, an uncaught throw or unhandled rejection restarts the process for everyone.
Set the team rule for an Express 4 to 5 upgrade: drop the forwarding wrappers, ban throws in callbacks, and require awaited or explicitly caught promises.
## What the Express 5 router actually catches Every handler you register is invoked by the router that Express 5 bundles. The invocation does two things: - it wraps the call in **`try/catch`**, so anything thrown *while the handler function is running* is passed to `next(err)`; - it inspects the **return value**, and if that is a promise it attaches a rejection handler that calls `next(err)` with the rejection reason. If the reason is falsy (`throw undefined` in an `async` function, `Promise.reject()`), the router substitutes `new Error('Rejected promise')` so the error handler still receives an error. An `async` function always returns a promise, and anything thrown inside it, including a rejected `await`, rejects that promise. So an `async` handler is covered end to end with no wrapper. The guide puts it as: handlers that return a Promise call `next(value)` automatically when they reject or throw. What the router cannot do is observe work that is neither part of the synchronous call nor part of the returned promise. ## The checkout route, failure by failure Take a checkout endpoint that loads the cart from a database client returning promises, reads a receipt template with a callback-based file API, and fires an audit write. | Failure | Reaches error middleware? | What to write | |---|---|---| | `throw` in the handler body | yes | nothing extra | | `await db.findCart()` rejects in an `async` handler | yes, in Express 5 | nothing extra | | `return db.findCart().then(...)` rejects | yes, in Express 5 | return the promise | | `fs.readFile(path, (err) => ...)` reports `err` | only if you pass it | `if (err) return next(err)` | | `throw err` inside that callback | no, it crashes the process | call `next(err)` instead | | `db.audit(...).then(...)` started but not returned | no, unhandled rejection | end it with `.catch(next)` or `await` it | | `throw` inside a `setTimeout` callback | no, it crashes the process | `try/catch` inside, then `next(err)` | ## Failures you still route yourself The common thread is that the error happens **later, on a different call stack**, after the handler function has already returned: - **Error-first callbacks.** Node's callback APIs never throw their errors; they hand them to the callback as the first argument. Express cannot know the callback exists. Check `err` and call `next(err)`. When the callback carries only an error, passing `next` itself as the callback (`fs.writeFile(path, data, next)`) works too. - **Throwing inside a callback.** The throw unwinds the callback's own stack, which has no Express frame on it, so it becomes an uncaught exception. - **Un-returned promise chains.** If the handler starts a chain and does not return it, the router never sees the promise. Without a final `.catch(next)` the rejection is unhandled, and Node 24's default `--unhandled-rejections=throw` mode turns that into a crash. - **Timers and other deferred work.** Code in `setTimeout` runs after the handler returned; wrap it in `try/catch` and pass the error to `next`. Making the handler `async` changes none of these: its promise settles on its own schedule, independently of the callback or the floating chain, so the router's rejection handler never sees their errors. ## What changed from Express 4 Express 4's router called the handler and ignored its return value. A rejected promise from an `async` handler was therefore never forwarded: the request never reached error middleware, and the rejection surfaced only as a process-level unhandled rejection. Teams compensated with `.catch(next)` at the end of every chain or a small wrapper function around every `async` handler. The Express 5 migration guide records the change: rejected promises from middleware and handlers are now forwarded to error-handling middleware as if `next(err)` had been called. When upgrading, those wrappers can go; the callback and timer rules above did not change. ## Practical rules 1. Write handlers as `async` functions and `await` every promise you start, so every failure joins the returned promise. 2. For callback APIs, check `err` and call `next(err)`; never `throw` from the callback. 3. If a chain must run without being awaited, give it its own `.catch(next)`, but only when the request has not been answered yet. 4. Keep `next` in the signature of any handler that uses callbacks or timers, since `async` alone does not cover them. A senior answer also names the consequence of each escape: a missed `next(err)` hangs the request, while an uncaught throw or unhandled rejection takes down the whole process and every request in flight with it.
- Why doesn't making the receipt handler async fix an error thrown inside the fs.readFile callback?The async function's promise settles when its own body finishes, which is before the file read completes. The callback runs later on a fresh call stack that is not part of that promise, so a throw there is an uncaught exception. The fix is the same as in a plain handler: check `err` and call `next(err)`.
- When upgrading from Express 4, can the wrapper around every async handler be removed?Yes, for forwarding: Express 5 calls `next(err)` on a returned rejection itself. Check first that the wrapper did nothing else, such as mapping errors or adding context, and keep any `.catch(next)` on chains that are not returned from the handler, because Express 5 still cannot see those.
- What does the error handler receive when an Express 5 async handler runs `throw undefined`?An `Error` whose message is 'Rejected promise': the router substitutes it for a falsy rejection reason. A synchronous `throw undefined` is different: it reaches `next(undefined)`, which Express reads as no error at all, so the request carries on and usually ends in the built-in 404.
- Express 5 still needs a wrapper around every async route handler.
- Any error raised during a request, even inside a callback, reaches error middleware.
- Declaring the handler async also catches throws inside its fs callbacks.
- A promise chain started in the handler is forwarded even when it is not returned.
- Passing callback errors to next(err) is optional in Express 5.
Assumes Express 5, whose router forwards a handler's returned rejection to next(err); Express 4 ignored returned promises, so async handlers needed .catch(next) or a wrapper.