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.

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:
(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.
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.
// repro.js
async function main() {
throw new Error("boom");
}
main(); // no await, no catch
console.log("still running");node repro.js
# still running
# UnhandledPromiseRejection ... Error: boom
# Node 22: process exits with code 1node --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| Mode | Behaviour | Exit code | Use |
|---|---|---|---|
throw | raises an uncaught exception | 1 | default, production |
strict | same as throw, no legacy warning noise | 1 | explicit in CI |
warn | prints UnhandledPromiseRejectionWarning | 0 | legacy scripts only |
none | prints nothing | 0 | debugging, 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.
| Source | Why the rejection is unhandled | Fix |
|---|---|---|
asyncFn() called without await | returned promise dropped | await, or void asyncFn().catch(handle) |
array.forEach(async ...) | forEach ignores returned promises | for...of with await, or Promise.all |
.then(fn) where fn throws | a new rejected promise, no handler | add .catch, or await inside try |
| event emitter callback | emitter does not await listeners | wrap the body in try/catch |
setTimeout(async () => ...) | timer ignores the promise | catch inside the callback |
Promise.all with one failure | other rejections still surface individually | allSettled, or catch each |
stream pipeline callback error | callback throws instead of calling back | call callback(err) |
| worker or child process exit handler | async work in exit handler | keep handlers synchronous, use close |
Key Comparison Table
| Approach | Catches sync throw | Catches rejection | Keeps process alive |
|---|---|---|---|
try { await fn() } catch | yes | yes | yes, if handled |
fn().catch(e => ...) | no, if fn throws before returning | yes | yes |
process.on("unhandledRejection") | no | only after it escapes | only because you prevent exit |
process.on("uncaughtException") | yes | no | risky, state may be corrupt |
domain module | yes | yes | deprecated, do not use |
Promise.allSettled | n/a | returns results, no rejection | yes |
| Symptom | Probable cause | Confirm with |
|---|---|---|
| Process exits 1 with no request log | unhandled rejection in a startup task | run with --trace-uncaught, read the stack |
| Warning appears once, app continues | Node 14 or warn mode | node -p process.version |
| Rejection logged but HTTP 200 returned | fire-and-forget write behind the response | search for .then( without .catch( |
| Crash only under load | rejected promise from a pool or queue | add process.on("unhandledRejection") logging |
| Crash inside a library | library calls your callback asynchronously | reproduce with --unhandled-rejections=strict |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Fire-and-forget async calls
// 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:
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
// 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
emitter.on("job", async (job) => {
try {
await process(job);
} catch (err) {
emitter.emit("job:error", err, job);
}
});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
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
// 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
// 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=warnin production only defers it. - Catching too late.
tryaround a function that returns a promise withoutawaitdoes not catch its rejection. Theawaitmust be inside thetry. process.exit()inside the handler. It skips pending writes, flushes and connection closes. Setprocess.exitCodeand 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 anErrorso the log carries a stack. - Async
uncaughtExceptionhandlers. 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
--importwith 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 documentationThe Node.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js: ERR_DLOPEN_FAILED invalid ELF header
Invalid ELF header means a native addon was built for another OS or architecture. Rebuild it inside the target image instead of copying node_modules.
Node.js ERR_INVALID_ARG_TYPE: the argument must be of type
ERR_INVALID_ARG_TYPE is Node's validator naming a wrong argument. Read the quoted argument, validate at the boundary and default env values.
ERR_MODULE_NOT_FOUND: Cannot find module imported from an ESM file
ESM resolves specifiers literally: extensions are required, directories do not resolve to index files, and exports maps block deep imports.
Node.js 26 upgrade: rmdir, native addons and removed flags
Three breaks stop a deploy: rmdir with recursive throws, the transform-types flag is gone, and the module ABI moved to 147.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.