Error explained
Unhandled promise rejection in Node.js
Since Node.js 15, a promise that rejects with no handler crashes the process by default. The fix is to await or catch every promise, and to log what still slips through.
3 min read10 sectionsUpdated
On this page
// 1. missing await: the rejection escapes the try/catch
try { saveOrder(order); } catch (e) { /* never runs */ }
// 2. fire and forget without a catch
sendWelcomeEmail(user);
// 3. async callback in an API that ignores the returned promise
items.forEach(async (i) => { await process(i); });try { await saveOrder(order); } catch (e) { logger.error({ err: e }, 'save failed'); throw e; }
sendWelcomeEmail(user).catch((e) => logger.warn({ err: e }, 'email failed'));
for (const i of items) await process(i); // sequential
await Promise.all(items.map((i) => process(i))); // parallel, fails fast
await Promise.allSettled(items.map((i) => process(i))); // parallel, collect failuresDo not use this handler to keep running as if nothing happened: the process may be in an inconsistent state. Log, report and restart. Lint rules such as @typescript-eslint/no-floating-promises find missing awaits before they reach production.
Catching it in production
A crash shows as restarts and a burst of 502s or failed checks. Restart counts, uptime checks and the fatal log line (with the stack) together point straight at the promise.
VitalRix error tracking groups exceptions recorded on OpenTelemetry spans into issues with counts, first and last seen, affected endpoints and versions, and marks an issue as regressed if it comes back after being resolved. Alert rules on error rate per service or endpoint route the problem to the right team before customers report it.
Express and older frameworks
Express 4 does not catch errors thrown in async route handlers; the rejection escapes and can crash the process. Wrap handlers or pass errors to next. Express 5 handles rejected promises from handlers for you.
const wrap = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
app.get('/orders/:id', wrap(async (req, res) => {
res.json(await loadOrder(req.params.id));
}));// log with context and exit: since Node 15 an unhandled rejection crashes the process by default
process.on('unhandledRejection', (reason) => {
console.error('Unhandled promise rejection', reason);
process.exitCode = 1;
});
// the usual fix: await the promise (or return it) inside a try/catch
app.post('/orders', async (req, res, next) => {
try {
const order = await createOrder(req.body);
res.status(201).json(order);
} catch (err) {
next(err); // Express 4 does not catch async errors by itself
}
});| Pattern | Why it leaks rejections |
|---|---|
| Calling an async function without await | Its rejection has no handler |
| forEach with an async callback | forEach ignores the returned promises; use for...of or Promise.all |
| Promise.all without a catch | The first rejection is unhandled |
| Async Express 4 handlers without try/catch | The error never reaches the error middleware |
Can I change the crash behaviour?
The --unhandled-rejections flag can set warn mode, but crashing is the safer default. Fix the code instead.
Does this apply to browsers?
Browsers fire an unhandledrejection event instead of crashing. Report it to your error tracking like any other error.
Related reading
- OpenTelemetry for NestJS: Trace a NestJS service with OpenTelemetry: load the SDK before Nest boots, instrument HTTP, Express and NestJS core, and export JSON to VitalRix.
- Error: socket hang up: Why Node.js reports "socket hang up", from servers closing connections and timeouts to proxies and TLS problems, with steps to find the cause.
- OpenTelemetry for Express.js: setup guide: Add OpenTelemetry tracing to Express.js: auto-instrumentation, why load order matters, adding custom attributes and fixing the missing spans people run into.
- "Aw, Snap!" in Chrome: how to fix it: Fix Chrome’s "Aw, Snap!" page crash: out of memory, extensions, GPU problems and security software, plus how developers find the page that crashes tabs.
- EADDRINUSE: address already in use and how to fix it: Fix EADDRINUSE in Node.js and other servers: find which process holds the port, handle old processes after a crash and avoid race conditions in restarts.
- EMFILE: too many open files in Node.js: Fix EMFILE too many open files in Node.js: leaked sockets and streams, unbounded concurrent file reads, ulimits and file watchers, with lsof commands.
Watch your own site and services with VitalRix
Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.