Express error handling and async routes
Error middleware, how Express 5 forwards rejected promises to it automatically, custom HTTP errors and the headersSent case.
Express routing and middlewareHandling uncaught errors and rejections
Express error handling and async routes
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Express error middleware has four parameters, `(err, req, res, next)`, and is registered after the routes. Express calls it when a handler throws, or calls `next(err)`.
- In Express 5, a handler that returns a rejected promise, including any `async` function that throws, passes the error to `next(err)` automatically. The `asyncHandler` wrappers and `try`/`catch` boilerplate that Express 4 needed are no longer required.
- Give errors a `status` (and an `expose` flag) so one central handler can turn them into responses. Do not leak internal messages for 5xx errors.
- If `res.headersSent` is true, you cannot send a new response. Call `next(err)` so Express's default handler closes the connection.
- Add a 404 handler that calls `next(new HttpError(404, ...))` before the error handler, so unknown routes and thrown errors share one response format.
Errors need one front door
Without structure, every handler grows its own try/catch and its own response shape. Express offers a single place: error-handling middleware. It looks like normal middleware with one extra leading parameter.
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
const status = err.status ?? 500;
if (status >= 500) console.error('ERR', err.message);
res.status(status).json({
error: err.expose ? err.message : 'Internal Server Error',
details: err.details,
});
});
Register it after the routes. Express calls it when a handler throws synchronously, when a handler calls next(err), or (in Express 5) when an async handler rejects.
What Express 5 fixed
Express 4 only caught synchronous throws. An async handler that threw returned a rejected promise that nobody looked at, so the client waited forever and the process logged an unhandled rejection. People worked around it with a wrapper:
// Express 4 era
const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
app.get('/users/:id', asyncHandler(async (req, res) => { /* ... */ }));
Express 5 does that internally. A handler that returns a promise has its rejection passed to next(err):
class HttpError extends Error {
constructor(status, message, details) {
super(message);
this.status = status;
this.details = details;
this.expose = status < 500; // only 4xx messages are safe to show
}
}
app.get('/async-throw', async () => { throw new HttpError(418, 'teapot'); });
app.get('/async-reject', async () => { await Promise.reject(new HttpError(404, 'no such user')); });
app.get('/sync-throw', () => { throw new Error('sync boom'); });
I ran all three on Express 5.3. Responses: 418 {"error":"teapot"}, 404 {"error":"no such user"}, and 500 {"error":"Internal Server Error"}, with the real message only in the server log. The same applies to router-level handlers and middleware. Callback-style code (an event or a setTimeout) is still outside this: an error thrown there never goes through Express, so wrap it and call next(err) yourself.
A 404 is an error too
Put a catch-all just before the error handler so that unknown routes use the same response format:
app.use((req, res, next) => next(new HttpError(404, `Cannot ${req.method} ${req.path}`)));
A request to /missing returned 404 {"error":"Cannot GET /missing"} through the central handler.
When the response has already started
If an error occurs after res.write() has sent part of the body, the status code and headers are gone. Trying res.status(500).json(...) would throw. That is the reason for the first line of the handler:
if (res.headersSent) return next(err);
Passing the error on makes Express’s built-in handler close the connection. In a test that wrote 'partial' and then called next(new Error('mid-stream')), the client’s request failed with a socket error and the server logged the stack. That is the correct outcome, since the client must find out the body is incomplete.
Design notes
- Operational versus programmer errors.
HttpErrorcarries intentional, safe messages. Everything else is a bug and gets a generic 500. This follows the same split as uncaught error handling. - Body parsing errors.
express.json()raises errors witherr.typesuch asentity.parse.failed(400) andentity.too.large(413). Map them in the handler. - Validation errors are covered in the REST API lesson. For response shapes across a whole API, see structured error handling and RFC 7807.
- Logging. Log server errors with the request ID; see AsyncLocalStorage and pino.
What the video covers
Coding Garden’s “Express v5 Is HERE” is a 10-minute excerpt from a livestream, published September 2024. Its description says CJ shows all the changes in Express 5.0.0, and links the official migration guide, a starter repository and the DefinitelyTyped v5 types pull request. It is a tour of what changed, not an error-handling tutorial, so it is the right place to see the version differences but does not cover central error handlers in depth. I could not read a transcript to confirm which changes it dwells on. The error handler, the HttpError pattern and the headersSent case are from this page. Traversy’s chapter on a custom error handler, in “go deeper”, is a build-along but is Express 4-era.
Where this fits
This follows routing and middleware and feeds building a REST API, where validation failures become 400 responses.
Check yourself
In Express 4 you wrote `app.get('/x', asyncHandler(async (req, res) => {...}))`. What do you need in Express 5?
Nothing extra. Express 5 awaits the promise a handler returns and forwards a rejection to `next(err)` itself, so `app.get('/x', async (req, res) => {...})` that throws reaches the error middleware. Express 4 would leave the request hanging and raise an unhandled rejection.
Why does an error handler need exactly four parameters?
Express identifies error middleware by its arity. A function with four parameters is registered as an error handler, and one with three is a normal middleware. If you drop the unused `next`, Express treats it as ordinary middleware and your errors skip it.
An error is thrown after `res.write('partial')` has already sent data. What should the error handler do?
Check `res.headersSent`. The status and headers are already out, so you cannot send a clean error response. Call `next(err)` and let Express's default handler destroy the connection, which the client sees as a failed request. In a test the client got `UND_ERR_SOCKET`.
How should a handler report 'user not found' versus an unexpected bug?
Throw an error carrying a 4xx `status` and a safe message for the first, such as a 404 `HttpError`, and let the handler return that message. For the bug, return a generic 500 body, log the real error, and do not expose its message.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.