Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js: UnhandledPromiseRejectionWarning and ERR_UNHANDLED_REJECTION

Since Node 15 an unhandled rejection crashes the process. Await or return every promise, catch async callbacks and shut down cleanly when one escapes.

~5 min readNode.js
#nodejs#promises#error-handling#async
Bold white headline reading UNHANDLED REJECTION beside a cyan promise cube falling past an amber void.

Introduction & Quick Summary

A service that ran for weeks dies at 03:00 with no error in the access log, and the crash dump starts like this:

code
(node:48213) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 10.0.0.7:5432 (node:48213) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict`.

Quick answer: a promise rejected and nothing was attached to handle it. Since Node.js 15 the default is to raise the rejection as an uncaught exception, so the process exits with ERR_UNHANDLED_REJECTION and a non-zero code instead of only printing a warning.

js
process.on("unhandledRejection", (reason, promise) => { logger.fatal({ reason }, "unhandled rejection"); process.exitCode = 1; });

That handler is a safety net for logging and shutdown, not a fix. The durable fix is to await or return every promise, wrap the right scope in try/catch, and make error paths in callbacks and event emitters explicit. This guide covers the runtime modes, the eight shapes that produce the error most often, and how to shut down cleanly when one escapes anyway.

Core Mechanics, Signatures & Reproducible Setup

A promise has two ways to be observed: await, .then(..., ...), or .catch(...). If none happens before the microtask queue drains and the promise is rejected, Node emits unhandledRejection on process. If no listener exists, the default mode applies.

js
// repro.js async function main() { throw new Error("boom"); } main(); // no await, no catch console.log("still running");
bash
node repro.js # still running # UnhandledPromiseRejection ... Error: boom # Node 22: process exits with code 1
bash
node --unhandled-rejections=warn repro.js # warning only, exit 0 node --unhandled-rejections=none repro.js # silent, exit 0, do not use in production node --unhandled-rejections=throw repro.js # default since Node 15
ModeBehaviourExit codeUse
throwraises an uncaught exception1default, production
strictsame as throw, no legacy warning noise1explicit in CI
warnprints UnhandledPromiseRejectionWarning0legacy scripts only
noneprints nothing0debugging, never ship

process.on("unhandledRejection") receives (reason, promise) and cancels the default crash, which is exactly why a careless global handler hides outages. Register one handler at the top of the entry point, log with the request or job id, set process.exitCode, and let the process finish in-flight work.

SourceWhy the rejection is unhandledFix
asyncFn() called without awaitreturned promise droppedawait, or void asyncFn().catch(handle)
array.forEach(async ...)forEach ignores returned promisesfor...of with await, or Promise.all
.then(fn) where fn throwsa new rejected promise, no handleradd .catch, or await inside try
event emitter callbackemitter does not await listenerswrap the body in try/catch
setTimeout(async () => ...)timer ignores the promisecatch inside the callback
Promise.all with one failureother rejections still surface individuallyallSettled, or catch each
stream pipeline callback errorcallback throws instead of calling backcall callback(err)
worker or child process exit handlerasync work in exit handlerkeep handlers synchronous, use close

Key Comparison Table

ApproachCatches sync throwCatches rejectionKeeps process alive
try { await fn() } catchyesyesyes, if handled
fn().catch(e => ...)no, if fn throws before returningyesyes
process.on("unhandledRejection")noonly after it escapesonly because you prevent exit
process.on("uncaughtException")yesnorisky, state may be corrupt
domain moduleyesyesdeprecated, do not use
Promise.allSettledn/areturns results, no rejectionyes
SymptomProbable causeConfirm with
Process exits 1 with no request logunhandled rejection in a startup taskrun with --trace-uncaught, read the stack
Warning appears once, app continuesNode 14 or warn modenode -p process.version
Rejection logged but HTTP 200 returnedfire-and-forget write behind the responsesearch for .then( without .catch(
Crash only under loadrejected promise from a pool or queueadd process.on("unhandledRejection") logging
Crash inside a librarylibrary calls your callback asynchronouslyreproduce with --unhandled-rejections=strict

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Fire-and-forget async calls

js
// wrong: rejection escapes, nothing owns it router.post("/orders", (req, res) => { saveOrder(req.body); // async, no await res.status(201).end(); }); // right: await and handle router.post("/orders", async (req, res, next) => { try { await saveOrder(req.body); res.status(201).end(); } catch (err) { next(err); } });

When the work must happen after the response, own the promise explicitly:

js
res.status(202).end(); void saveOrder(req.body).catch((err) => logger.error({ err }, "order save failed"));

void documents the intentional drop; .catch keeps it from reaching process.

2. forEach with async callbacks

js
// wrong: forEach ignores the promises ids.forEach(async (id) => { await sync(id); }); // right for (const id of ids) await sync(id); // or, bounded concurrency await Promise.all(ids.map((id) => sync(id)));

Promise.all rejects on the first failure while the others keep running; each still has a handler because all attaches one. With thousands of ids, chunk them to avoid exhausting sockets.

3. Event emitters and streams

js
emitter.on("job", async (job) => { try { await process(job); } catch (err) { emitter.emit("job:error", err, job); } });
js
import { pipeline } from "node:stream/promises"; try { await pipeline(readable, transform, writable); } catch (err) { logger.error({ err }, "pipeline failed"); }

EventEmitter does not await listeners and does not know they are async. A throwing async listener becomes an unhandled rejection. The promise version of pipeline is safer than the callback version, where throwing inside the callback leaves the stream in an undefined state.

4. A global handler that helps instead of hiding

js
let shuttingDown = false; process.on("unhandledRejection", (reason) => { logger.fatal({ err: reason }, "unhandled rejection"); if (shuttingDown) return; shuttingDown = true; process.exitCode = 1; server.close(() => process.exit(1)); setTimeout(() => process.exit(1), 10_000).unref(); });

Log first, then stop accepting work, then exit with a non-zero code so the supervisor restarts the pod. Swallowing the rejection and staying up is how a service keeps serving 500s for hours.

5. Framework-level handling

js
// Express 5 forwards rejected promises to the error middleware automatically app.get("/user/:id", async (req, res) => { const user = await findUser(req.params.id); // throws -> next(err) res.json(user); });

Express 4 needs try/catch or a wrapper such as express-async-errors, because a rejected handler is invisible to the router. Fastify, Koa and Nest each have their own hook; check that the async handler is registered as async, not as a callback returning a promise.

6. Workers, tests and startup tasks

js
// worker.js process.on("unhandledRejection", (err) => { parentPort.postMessage({ type: "fatal", message: String(err) }); process.exit(1); });

Test runners fail a suite on unhandled rejections, and a rejection raised after a test finishes is attributed to the next test, which makes failures look random. Await every promise a test creates, and use fake timers for delayed work. In startup code, void main().catch(...) at the entry point is the pattern that keeps a rejected migration from becoming a silent zombie. Use the status code reference when mapping these failures to HTTP responses, and the JSON formatter to check the payload of the error your logger emits.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Relying on the warning. On Node 15 and later this is fatal by default; code that survived years on Node 14 crashes on upgrade. That is a deliberate change, and --unhandled-rejections=warn in production only defers it.
  • Catching too late. try around a function that returns a promise without await does not catch its rejection. The await must be inside the try.
  • process.exit() inside the handler. It skips pending writes, flushes and connection closes. Set process.exitCode and close the server instead.
  • One handler to rule them all. A handler that only logs hides bugs. Count them, alert on the counter, and treat any occurrence as a defect.
  • Rejecting with non-Errors. Promise.reject("failed") produces a stack-less rejection; always reject with an Error so the log carries a stack.
  • Async uncaughtException handlers. The handler itself cannot await. Work scheduled inside it may never run before exit.
  • Unhandled rejections in dependencies. A library that starts background work on import can reject before your handler is registered. Register the handler as the first statement of the entry file, before imports that start work, or use --import with a small preload.
  • TypeScript and @typescript-eslint/no-floating-promises. Lint rule that flags exactly these drops; enabling it catches most cases before runtime.

Unhandled rejections are a symptom of unowned asynchrony. Awaiting, returning, or explicitly catching every promise at the point where it is created removes the class of bug rather than the message.

Official documentation: process events and Node.js CLI options.

Official references

primary documentation

The Node.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.