Skip to content
jshacks.dev
Async

Unhandled Promise Rejections and How Runtimes Report Them

See what an unhandled promise rejection is, how Node.js, Deno, Bun and browsers report it, and how to find and prevent the ones that crash a process.

6 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite and TypeScript logos.

A rejected promise that nobody handles is the asynchronous version of an uncaught exception, and it was ignored for years because nothing happened when it occurred. Browsers logged a warning to the console. Early Node.js versions printed a deprecation notice and carried on. Since Node.js 15 the default is to crash the process, which turned a harmless-looking omission into an outage. This post explains what counts as unhandled, when each runtime decides that a rejection is unhandled, what Node.js 24 does by default and how to change it, the events you can listen to in Node.js and browsers, and the code patterns that produce the problem. It finishes with a defensive setup for production.

What counts as unhandled

A promise is rejected when it settles with a reason, and it is handled when some handler is attached to it, a catch, a then with a second argument or an await inside a try. A rejection becomes "unhandled" if the promise is rejected and no handler is attached by the time the runtime checks.

JavaScript
const failing = Promise.reject(new Error("nobody is listening"));

console.log("promise created, no handler attached");
Text
promise created, no handler attached

In Node.js 24, this program prints the line, then crashes with an error report that includes the message and a stack trace, and exits with code 1. The check happens after the microtask queue is drained, so a handler attached in the same turn, even a bit later in the code, still counts.

JavaScript
const late = Promise.reject(new Error("handled just in time"));

queueMicrotask(() => {
  late.catch((error) => console.log("handled:", error.message));
});
Text
handled: handled just in time

The handler was attached during the microtask drain, before the check, so no report appeared. Attaching one in a later macrotask, such as a setTimeout, is too late, and Node.js reports the rejection first, then reports it as handled late through a separate event.

What Node.js does by default

The --unhandled-rejections option sets the policy, and the default for Node.js 15 and later is throw. The rejection is raised as an uncaught exception, and if there is no uncaughtException handler the process exits with code 1. The available modes are:

ModeBehavior
throw (default)Emit unhandledRejection; if unhandled there, raise as an uncaught exception
strictRaise as an uncaught exception immediately, then emit the event if that is handled
warnPrint a warning for every unhandled rejection and continue
warn-with-error-codeWarn and set the exit code to 1
noneSilence them

Setting warn or none is a way to hide bugs, and it is worth using only temporarily while you find the sources. The default is the right policy for production: a process in an unknown state should not keep serving traffic.

The events

Node.js emits two events on process.

JavaScript
process.on("unhandledRejection", (reason, promise) => {
  console.log("unhandled rejection:", reason.message);
});

process.on("rejectionHandled", (promise) => {
  console.log("a rejection was handled late");
});

const p = Promise.reject(new Error("too late for the check"));

setTimeout(() => p.catch(() => {}), 10);
Text
unhandled rejection: too late for the check
a rejection was handled late

With a listener for unhandledRejection, the default crash does not happen, since the event counts as handled. That makes the handler a place for your own policy: log it with context, report it to your error tracker and decide whether to exit. A common production choice is to log, then exit after a short delay so the supervisor restarts the process.

JavaScript
process.on("unhandledRejection", (reason) => {
  console.error("fatal: unhandled rejection", reason);
  process.exitCode = 1;
  setTimeout(() => process.exit(), 1000).unref();
});
Text
fatal: unhandled rejection Error: boom

The output shows the reason you would see for a rejection with an Error named boom, plus its stack trace lines, which are omitted here.

Other runtimes

Browsers fire an unhandledrejection event on window, with the promise and the reason on the event object, and log a message to the console. Calling event.preventDefault() suppresses the console message. A rejectionhandled event reports a late handler.

JavaScript
window.addEventListener("unhandledrejection", (event) => {
  console.log("unhandled:", event.reason);
  event.preventDefault();
});
Text
unhandled: Error: request failed

Deno follows the browser model, with the same event names on globalThis, and terminates the process on an unhandled rejection unless a listener calls preventDefault(). Bun emits the Node.js style unhandledRejection event and crashes by default as well. Service workers and web workers have their own unhandledrejection events on their global scope.

The usual causes

**A missing await.** The promise is created, the function moves on and its rejection has no handler.

JavaScript
async function save() {
  throw new Error("disk full");
}

async function main() {
  save(); // missing await, rejection is unhandled
  console.log("main finished");
}

main();
Text
main finished

After this line, Node.js 24 reports the error from save and exits with code 1. Putting await in front of save() makes the failure reject main instead, where a caller can handle it.

**A promise inside forEach.** The loop ignores the promises returned by an async callback, so each failure is unhandled.

**An event handler that is async.** A listener passed to emitter.on or addEventListener that throws returns a rejected promise that the emitter never looks at.

JavaScript
import { EventEmitter } from "node:events";

const emitter = new EventEmitter();
emitter.on("job", async () => {
  throw new Error("handler failed");
});

emitter.emit("job");
Text
(process exits with the unhandled rejection error for "handler failed")

For this case, Node.js has captureRejections: true on EventEmitter, which routes a rejected handler to the emitter's error event.

JavaScript
const safe = new EventEmitter({ captureRejections: true });

safe.on("error", (error) => console.log("routed to error event:", error.message));
safe.on("job", async () => {
  throw new Error("handler failed");
});

safe.emit("job");
Text
routed to error event: handler failed

Creating a rejected promise and handling it later. Storing Promise.reject(...) in a variable and attaching handlers after an await can trip the check. Attach a handler in the same turn, or create the promise at the point of use.

Branches in a chain. Handling p.then(a) does not handle p itself. If you attach .then(a) to a promise that rejects, the derived promise rejects too, and that one needs a handler.

Finding the source

The report includes the stack trace of the error object, which points to where the error was created, and not to where the promise was dropped. If the stack trace is useless, because the rejection used a string, Promise.reject("failed"), start with that: always reject with an Error. Then search for calls to promise-returning functions with no await, return or catch. A lint rule, @typescript-eslint/no-floating-promises for TypeScript or no-floating-promises in other setups, finds these statically. In Node.js, the --trace-uncaught flag prints a stack for the throw site of uncaught exceptions that were raised from unhandled rejections.

A production setup

A reasonable baseline has four parts. Keep the default crash policy. Install one unhandledRejection handler at the top of the program that logs structured information and reports it. Run under a supervisor that restarts the process. And turn on the floating promise lint rule, so the problem is caught before the code runs. If you are deliberately firing a promise and forgetting it, say so by attaching an explicit handler, promise.catch(logError), or by writing void promise.catch(...), so the next reader sees the decision.

Reviewing a codebase for the problem

A quick audit takes an afternoon. Turn on the floating promise rule in your linter and read the list of violations, since each one is a place where a rejection could go unhandled. Search for async callbacks passed to forEach, emitter.on, addEventListener and setTimeout, because none of those look at the returned promise. Search for Promise.reject( with a string argument and change those to Error objects. Then run the test suite with the strict mode, node --unhandled-rejections=strict, which surfaces rejections the moment they are created and makes a flaky pass into a clear failure. After that, keep the lint rule in CI so new ones cannot appear.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.