Skip to main content

Unhandled Promise Rejections in JavaScript: How to Catch the Errors Your Users Never Report

Robin Alex Panicker9 min read

An unhandled promise rejection is the quietest way a web app can break. A request fails, an async function throws, and nothing on screen tells the user what happened. The button just stops working, the spinner never ends, or the form submits nothing. Most users will not file a bug report. They reload, try once more, and leave. This post explains why these errors slip past the usual safety nets, how to catch every one of them in the browser, and how to find the code that caused them once they show up in production.

Prerequisites​

The code in this post runs as written with:

  • Any current version of Chrome, Edge, Firefox or Safari. The unhandledrejection event is supported in all of them.
  • Node.js 18 or later for the Node behavior described later in the post.
  • typescript-eslint with type-aware linting enabled for the no-floating-promises rule.
  • The Appxiom Web SDK (npm install @appxiom/web) if you want rejections captured with their activity trail. Setup steps are in the Web SDK installation guide.

What an unhandled promise rejection is​

A promise rejection is unhandled when a promise rejects and no .catch() handler or try/catch around an await is attached to it by the time the browser finishes its current round of microtasks. The browser then reports it, and in Chrome's console it looks like this:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')
at loadProfile (profile.js:14:28)

The important word is "in promise". The error did not stop your script the way a synchronous throw would. The code that started the async work has already returned, so execution carries on, and the only trace is a console line that nobody in production will ever see.

Why try/catch and window.onerror miss it​

Most teams have a global window.onerror handler and wrap risky code in try/catch. Neither of them sees a rejected promise in the common cases.

try/catch only catches a rejection when you await the promise inside the try block. Call an async function without await and the rejection escapes:

async function saveSettings(settings) {
const res = await fetch('/api/settings', {
method: 'POST',
body: JSON.stringify(settings),
});
return res.json();
}

try {
saveSettings(form); // no await: the rejection happens later, outside this block
} catch (err) {
showError(err); // never runs
}

window.onerror and the error event cover uncaught synchronous exceptions and resource load failures. Promise rejections go to a separate event, unhandledrejection, so an error dashboard built only on onerror has a blind spot exactly where modern async code lives.

The five patterns that cause most unhandled rejections​

In real codebases the same few patterns show up again and again.

PatternWhat goes wrongFix
Fire and forget callsAn async function is called from an event handler without await or .catch()Await it inside a try/catch, or chain .catch()
.then() without .catch()The chain has no rejection handler at the endEnd every chain with .catch()
Promise.allOne rejected promise rejects the whole callHandle it, or use Promise.allSettled
Async callbacks in forEachforEach ignores the returned promisesUse for...of with await, or Promise.all with map
Parsing the responseres.json() rejects with a SyntaxError when the server returns HTML or an empty bodyCheck res.ok and the content type before parsing

Two of these deserve a closer look because they surprise even experienced developers.

fetch does not reject on HTTP errors​

fetch resolves for any response the server sends, including a 404 or a 500. It rejects only when the request itself fails, for example on a network error, a CORS failure or an aborted request. So a 500 that returns an HTML error page sails through the fetch call and then rejects one line later in res.json():

// Before: a 500 with an HTML body becomes "Unexpected token '<'"
async function loadOrders() {
const res = await fetch('/api/orders');
return res.json();
}

// After: fail early with an error that says what happened
async function loadOrders() {
const res = await fetch('/api/orders');
if (!res.ok) {
throw new Error(`GET /api/orders failed with ${res.status}`);
}
return res.json();
}

The fixed version still throws, but it throws an error that names the endpoint and the status code. That turns a confusing SyntaxError in your logs into something you can act on.

Async loops that nobody awaits​

forEach does not wait for async callbacks, so any rejection inside them becomes unhandled:

// Before: three requests start, nobody waits, failures go unhandled
items.forEach(async (item) => {
await uploadItem(item);
});

// After: wait for every upload and handle failures in one place
const results = await Promise.allSettled(items.map((item) => uploadItem(item)));
const failed = results.filter((r) => r.status === 'rejected');
if (failed.length > 0) {
reportUploadFailures(failed.map((r) => r.reason));
}

Promise.allSettled waits for every promise and never rejects, so you decide what a partial failure means for the user instead of losing it.

How to catch every unhandled rejection with unhandledrejection​

The browser fires an unhandledrejection event on window for each rejection that reaches the end of its microtask turn without a handler. Listening for it gives you a single place to log what your local handlers missed:

window.addEventListener('unhandledrejection', (event) => {
const reason = event.reason;
const message = reason instanceof Error ? reason.message : String(reason);
const stack = reason instanceof Error ? reason.stack : undefined;

sendToLogging({
type: 'unhandledrejection',
message,
stack,
url: window.location.href,
});
});

A few details matter here:

  • event.reason is whatever the promise rejected with. If code calls reject('timeout') with a plain string, you get no stack trace at all. Always reject with an Error object.
  • Calling event.preventDefault() stops the browser from printing the default console message. Leave it out while you are still debugging.
  • A rejectionhandled event fires if a handler is attached to the same promise later. It is rare in practice, but it explains the odd case where a rejection is logged and then handled anyway.

In Node.js the default is stricter. Since Node 15 an unhandled rejection crashes the process, which is why server code tends to get fixed faster than browser code. In the browser nothing crashes, so the bug can live in production for months.

Why the global handler is only the start​

A global listener tells you that a rejection happened. It rarely tells you why. A message such as TypeError: Failed to fetch with a stack that ends inside a bundled vendor file says very little about which user action triggered it, which API call was in flight or whether it actually stopped anyone from finishing what they came to do.

That missing context is the expensive part. Here is an illustrative case. A checkout page logs a few hundred Failed to fetch rejections a day. The team assumes flaky mobile networks and moves on. The real cause is a payment config request that times out on one browser after a release, and every one of those rejections is a customer who could not pay. The count alone looked harmless. The journey it broke was not.

Find the rejections that cost you users. The Appxiom Web SDK captures errors automatically, including unhandled promise rejections, and records the activity trail and network calls around each one. Connect your coding agent to the Appxiom MCP server and ask: "Check Appxiom for the most frequent JavaScript errors and unhandled promise rejections on the web app." The agent gets the list with occurrence telemetry, and you decide which one to fix first.

Appxiom maps issues to the goals you define, such as checkout or sign up, and scores them with Goal Friction Impact. A rejection that fires on every page load but never blocks a goal ranks below one that stops payments. If you have not set goals up before, our post on Goal Friction Impact and the revenue cost of broken user journeys explains the idea, and session replay vs activity trail covers why a timestamped trail is often faster to debug from than a video.

A checklist for promise error handling​

Use this list in code review. Each item closes one of the gaps above.

  1. Every promise is either awaited inside try/catch or ends in .catch().
  2. Event handlers that call async functions handle their own errors, because nothing above them will.
  3. fetch calls check res.ok before reading the body.
  4. Code rejects with Error objects, never plain strings or objects, so every rejection has a stack.
  5. Parallel work uses Promise.allSettled when a partial failure is acceptable, and Promise.all only when one failure should cancel everything.
  6. Async loops use for...of with await or Promise.all over map, never forEach.
  7. A global unhandledrejection listener sends anything that slips through to your monitoring.
  8. Lint rules such as @typescript-eslint/no-floating-promises flag unawaited promises before they ship.

The lint rule is worth turning on even in a large existing codebase. It needs type information to run, and the first pass usually finds dozens of fire and forget calls, most of which are fine and some of which are the bug you have been chasing.

Catch them before your users give up​

Unhandled promise rejections are not exotic bugs. They come from a handful of everyday patterns, and each one has a direct fix. What makes them costly is that the browser keeps running, so nobody notices until a metric drops. Fix the patterns in review, add a global listener as a safety net, and track rejections against the journeys they interrupt so the one that blocks checkout never hides behind the ones that do not matter. Coding agents can do much of the fixing once they can see that production data, as we wrote in your AI coding agent can write the fix, but it can't see production.

To start capturing unhandled rejections from your own web app, follow the Appxiom Web SDK quickstart. It takes one npm install and a single init call.