Error Handling
Things go wrong: a database is down, input is invalid, a bug throws. Express routes all of these to error-handling middleware — a middleware with four parameters, (err, req, res, next).
How errors reach the handler
| Where the error happens | Express 5 behaviour |
|---|---|
throw in a synchronous handler |
caught, passed to the error handler |
rejected promise / throw in an async handler |
caught, passed to the error handler (new in v5) |
next(err) |
passed to the error handler |
error inside a callback or timer (setTimeout(() => { throw … })) |
not caught — crashes the process |
In Express 4 you had to wrap every async handler in try/catch or a helper; a rejected promise was simply lost. In Express 5 this just works.
Writing an error handler
Register it after all routes. Express recognises it by the four parameters — keep next in the signature even if you don't use it:
const express = require('express');
const app = express();
app.get('/sync', (req, res) => {
throw new Error('sync failure');
});
app.get('/async', async (req, res) => {
await new Promise((r) => setTimeout(r, 5));
throw new Error('async failure');
});
app.get('/manual', (req, res, next) => {
next(new Error('passed to next()'));
});
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message, path: req.path });
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const p of ['/sync', '/async', '/manual']) {
const res = await fetch(base + p);
console.log(res.status, await res.text());
}
server.close();
});500 {"error":"sync failure","path":"/sync"}
500 {"error":"async failure","path":"/async"}
500 {"error":"passed to next()","path":"/manual"}
HTTP errors with a status
Throwing a plain Error always gives 500. Define an error class that carries a status code, and let the handler use it:
const express = require('express');
class HttpError extends Error {
constructor(status, message, details) {
super(message);
this.status = status;
this.details = details;
}
}
const users = new Map([[1, { id: 1, name: 'Ana' }]]);
const app = express();
app.get('/users/:id', async (req, res) => {
const user = users.get(Number(req.params.id));
if (!user) throw new HttpError(404, 'User not found', { id: req.params.id });
res.json(user);
});
app.get('/crash', () => {
null.boom; // a real bug: TypeError
});
app.use((err, req, res, next) => {
const status = err.status ?? 500;
const body = { error: status < 500 ? err.message : 'Internal Server Error' };
if (err.details) body.details = err.details;
if (status >= 500) console.log('[logged]', err.name + ':', err.message);
res.status(status).json(body);
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
for (const p of ['/users/1', '/users/7', '/crash']) {
const res = await fetch(base + p);
console.log(p.padEnd(9), res.status, await res.text());
}
server.close();
});/users/1 200 {"id":1,"name":"Ana"}
/users/7 404 {"error":"User not found","details":{"id":"7"}}
[logged] TypeError: Cannot read properties of null (reading 'boom')
/crash 500 {"error":"Internal Server Error"}
Note: Never send
err.messageor stack traces of unexpected (5xx) errors to clients — they can reveal file paths, SQL or secrets. Log them on the server and reply with a generic message.
The 404 handler and the error handler
A typical app ends with two functions — first the "nothing matched" handler, then the error handler:
app.use((req, res) => res.status(404).json({ error: 'Not found' })); // 3 params: normal middleware
app.use((err, req, res, next) => { /* … */ }); // 4 params: error handlerWhen the response has already started
If an error happens while streaming a response, you can no longer change the status. Delegate to Express's default handler, which closes the connection:
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
res.status(err.status ?? 500).json({ error: 'Something went wrong' });
});Errors in callbacks
Express can't catch errors thrown later from a callback API. Wrap them in a promise (or use the promise version of the API) so the error flows through await:
const express = require('express');
const fs = require('node:fs/promises');
const app = express();
app.get('/config', async (req, res) => {
const text = await fs.readFile('does-not-exist.json', 'utf8'); // rejects → error handler
res.type('json').send(text);
});
app.use((err, req, res, next) => {
res.status(err.code === 'ENOENT' ? 404 : 500).json({ error: err.code });
});
const server = app.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}/config`);
console.log(res.status, await res.text());
server.close();
});404 {"error":"ENOENT"}
Checklist
| Do | Avoid |
|---|---|
throw/next(err) with a status property for expected errors |
sending different error shapes from every route |
| one central handler that formats all errors | leaking stack traces in production |
| log 5xx errors with request context | try/catch around every async handler (not needed in v5) |
use promise APIs (fs/promises) |
throwing inside setTimeout or event callbacks |
Test yourself
How does Express recognise error-handling middleware?
- It is named
errorHandler - It is registered with
app.error() - It declares four parameters
(err, req, res, next) - It is registered first
In Express 5, what happens when an async route handler throws?
- The request hangs
- The process crashes
- The error is passed to the error-handling middleware
- Express retries the handler
Which error will Express NOT catch automatically?
throwin a sync handler- A rejected
awaitin an async handler throwinside asetTimeoutcallbacknext(new Error())