Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

This try/catch Doesn't Catch: The Promise Mistake That Crashes Node

Quick quiz. Does the catch block run? async function loadDashboard() { try { const userP = getUser(); // takes 300 ms, succeeds const ordersP = getOrders(); // fails after 100 ms const user = await

Quick quiz. Does the catch block run?

async function loadDashboard() {
  try {
    const userP = getUser();      // takes 300 ms, succeeds
    const ordersP = getOrders();  // fails after 100 ms
    const user = await userP;
    const orders = await ordersP;
    return { user, orders };
  } catch (err) {
    console.log('caught:', err.message);
  }
}

Both requests start in parallel, everything is inside try, and the error should land in catch. Take a guess before you scroll. 👇

.

.

.

No. In Node 22 the process dies with exit code 1, and caught: is never printed:

Error: orders failed

Node.js v22.19.0

Why the catch never runs

Node has a simple rule. When a promise rejects, it lets the current batch of microtasks finish, then checks whether anything handles the rejection. If nothing does, it raises an unhandled rejection. Since Node 15 the default is to treat that like an uncaught exception, and the process exits.

await attaches a handler, but only to the promise you're currently awaiting, and only when execution reaches that line:

time what happens
0 ms both requests start; await userP attaches a handler to userP only
100 ms ordersP rejects, and nothing is handling it → crash
300 ms userP resolves; await ordersP would attach the handler now. Too late.

So try/catch protects the await, not the promise. If a promise was created earlier and rejects before you get to it, the catch block is irrelevant.

Why haven't I seen this in the browser? Browsers just log Uncaught (in promise) in the console and keep going. The same code that "works" on the frontend can take down a Node server, an SSR render, or a build.

How it bit me

My dev server started crashing on startup. Not every time: only on bad Wi-Fi.

TypeError: fetch failed
  [cause]: ConnectTimeoutError: Connect Timeout Error (timeout: 10000ms)
    code: 'UND_ERR_CONNECT_TIMEOUT'

Node.js v22.19.0

The culprit was a config helper that started a request as soon as the file was imported:

// config.js: imported when the server starts
const settings = fetch('https://api.example.com/settings').then(res => res.json());

export async function getSettings() {
  try {
    return await settings;
  } catch (err) {
    console.error('Could not load settings', err);
    return null;
  }
}

It's the same bug as the quiz: created now, awaited later. It only crashed sometimes for two reasons:

  • It's a race. On a fast network the request succeeded, or failed after something was already awaiting it. On slow Wi-Fi my DNS lookups took 3–7 seconds, and Node's built-in fetch gives up connecting after 10, so the request failed before anyone was awaiting it.
  • Startup is the danger window. Many servers install their own unhandledRejection handler once they're up (the Next.js dev server does), so later rejections are only logged. A rejection during import happens before that safety net exists.

Where this bug hides

  1. "Start in parallel, then await one by one": the quiz. It looks like good, performance-minded code, which is why it's so common.
  2. Promises created when a module loads: config, feature flags, settings, "warm the cache on import". Watch for const x = fetch(...) at the top level of a file.
  3. Cached promises: cache.set(key, fetchThing()), used much later.

Lint won't save you here. @typescript-eslint/no-floating-promises flags promises you never use. A promise saved to a variable counts as "used", even if nothing handles it in time.

Three fixes

1. Await things together with Promise.all (or allSettled)

const [user, orders] = await Promise.all([getUser(), getOrders()]);

Promise.all attaches handlers to every promise immediately. You keep the parallelism, and the catch works: in my test this version printed caught: orders failed and exited cleanly. Use Promise.allSettled if you want partial results.

2. Handle the rejection where the promise is created

const settings = fetch('https://api.example.com/settings')
  .then(res => res.json())
  .catch(err => {
    console.error('Could not load settings', err);
    return null; // callers get null instead of a crash
  });

The promise now always resolves, so it can never go unhandled. Callers just need to handle null.

3. Don't start it until someone asks (lazy + cached)

let settingsPromise;

export function getSettings() {
  settingsPromise ??= fetchSettings().catch(err => {
    settingsPromise = undefined; // don't cache the failure, allow a retry
    throw err;
  });
  return settingsPromise;
}

Every caller awaits the promise as soon as it gets it, so a handler always exists when the promise rejects. Clearing the cache on failure means one bad request doesn't stick forever.

Also worth adding: fetch(url, { signal: AbortSignal.timeout(5000) }). It doesn't fix the bug, but it makes failures fast and predictable.

Bonus: reproduce "only on bad Wi-Fi" on demand

You can't fix a bug you can't trigger. Node's --require flag runs a file before your app starts, so you can use it to slow down DNS for a single host:

// slow-dns.cjs (for testing only)
const dns = require('dns');
const lookup = dns.lookup;

dns.lookup = (host, ...args) =>
  host === 'api.example.com'
    ? setTimeout(() => lookup.call(dns, host, ...args), 15000) // +15s
    : lookup.call(dns, host, ...args);
NODE_OPTIONS="--require ./slow-dns.cjs" npm run dev

With this, every run crashed with the exact error from my bug report. With fix 2 applied, the same run logged the error and the server kept going. NODE_OPTIONS is inherited by child processes, so this works even when your framework starts its own worker processes.

TL;DR

  • try/catch around await protects the await, not the promise.
  • In Node 15+, a promise that rejects with no handler kills the process. Browsers only log it, so frontend habits hide the bug.
  • Red flags: "start in parallel, await one by one", fetch() when a module loads, cached promises.
  • Fixes: Promise.all, .catch() where the promise is created, or create it lazily.

Rule of thumb: if you create a promise, either await it right away or attach .catch right away.

Did you guess the quiz right? Tell me in the comments 👇

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.