← Back to JavaScript, page 7

javascript-0139 · Hard senior

What is an unhandled promise rejection, what happens when one occurs in Node.js and in the browser, and how do you prevent them?

A promise that rejects with no handler attached by the end of the current microtask processing is an unhandled rejection. Node.js emits unhandledRejection and, by default since version 15, treats it as an uncaught exception and exits with an error. Browsers fire an unhandledrejection event and log a console error. Prevent it by always awaiting or catching promises, never leaving floating promises, and adding a global handler for logging.

Full answer

A rejected promise is a failure that must be handled with catch, then(_, onRejected), or try and catch around await. If no handler is attached when the engine checks, the rejection is unhandled, which usually means a bug: an error that nobody sees.

Node.js: the process emits unhandledRejection (with the reason and the promise). Since Node.js 15, the default mode is throw: if there is no unhandledRejection listener, the rejection becomes an uncaught exception, which prints the error and exits with code 1. If a handler exists, Node.js calls it and continues. If a handler is attached later, rejectionHandled is emitted. Production code should log the error in the global handler and then treat it as fatal when the process state is uncertain (shut down gracefully and let the process manager restart it).

Browser: the window fires an unhandledrejection event (with event.reason and event.promise) and the console shows an error. event.preventDefault() suppresses the console message. Use it for error reporting.

Common causes of unhandled rejections:

  • A floating promise: calling an async function without await or catch.
  • array.forEach(async (x) => {...}): forEach ignores the returned promises, so errors escape the surrounding try. Use for...of with await, or Promise.all(array.map(...)).
  • new Promise(async (resolve) => ...): an error thrown inside an async executor becomes a rejection of a different promise that nobody has.
  • Event handlers and timers with async functions: errors are not caught by the code that registered them.
  • Promise.all with several rejections: after the first rejection, the others are handled internally by Promise.all, so they do not cause extra reports, but their errors are lost. Use allSettled when you need all outcomes.

Prevention: await everything or return it, add a final .catch to top-level promises (main().catch(handle)), enable a lint rule such as no-floating-promises (typescript-eslint) and no-misused-promises, and register global handlers to log what slips through. Do not use a global handler to hide errors.

javascript
const { spawnSync } = require('node:child_process');

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const events = [];

process.on('unhandledRejection', (reason) => events.push('unhandledRejection: ' + reason.message));
process.on('rejectionHandled', () => events.push('rejectionHandled (a handler was attached late)'));

async function main() {
  // 1. A rejection nobody handles
  Promise.reject(new Error('floating promise'));
  await wait(20);

  // 2. A handler attached too late: first reported, then marked as handled
  const late = Promise.reject(new Error('handled late'));
  await wait(20);
  late.catch(() => events.push('late catch ran'));
  await wait(20);

  // 3. forEach with an async callback: the try/catch does not see the error
  try {
    [1].forEach(async () => {
      throw new Error('inside forEach callback');
    });
    events.push('try block finished without catching the forEach error');
  } catch (error) {
    events.push('caught: ' + error.message);
  }
  await wait(20);

  // 4. The correct form: for...of with await
  try {
    for (const item of [1]) {
      await (async () => {
        throw new Error('inside for-of loop');
      })();
    }
  } catch (error) {
    events.push('caught: ' + error.message);
  }

  // 5. Promise.all rejects once; the other rejection is handled internally and lost
  try {
    await Promise.all([Promise.reject(new Error('first')), Promise.reject(new Error('second'))]);
  } catch (error) {
    events.push('Promise.all rejected with: ' + error.message);
  }
  await wait(20);

  console.log(events.join('\n'));

  // 6. Default behavior without a handler: a separate process exits with code 1
  const child = spawnSync(process.execPath, ['-e', "Promise.reject(new Error('no handler'))"]);
  console.log('exit code without a handler:', child.status);
  const withHandler = spawnSync(process.execPath, ['-e', "process.on('unhandledRejection', () => {}); Promise.reject(new Error('x'))"]);
  console.log('exit code with a handler:', withHandler.status);
}
main();

Run with Node.js v24.22.1 as js-139.js; two runs gave identical output. Output: unhandledRejection: floating promise unhandledRejection: handled late late catch ran rejectionHandled (a handler was attached late) try block finished without catching the forEach error unhandledRejection: inside forEach callback caught: inside for-of loop Promise.all rejected with: first exit code without a handler: 1 exit code with a handler: 0

Key points

  • A rejection with no handler when microtasks settle is unhandled; it usually hides a bug.
  • Node.js default since version 15: it becomes an uncaught exception and the process exits with code 1.
  • Browsers fire unhandledrejection and log an error; Node.js also has rejectionHandled for late handlers.
  • Typical causes: floating promises, async callbacks in forEach, async promise executors.
  • Prevent with await or catch everywhere, lint rules, and global handlers used for logging.

Common mistakes

  • Calling async functions without await or catch.
  • Using forEach with an async callback and expecting try and catch around it to work.
  • Writing new Promise(async (resolve, reject) => ...).
  • Using a global handler to silence errors instead of logging and fixing the cause.

Follow-ups

  • What is the difference between unhandledRejection and uncaughtException in Node.js?
  • Why does array.map with async callbacks plus Promise.all work where forEach does not?
  • How would you configure a lint rule to find floating promises?

Tips

  • Describe the Node.js default behavior and the browser event.
  • List the three usual causes: floating, forEach, async executor.
  • Say that global handlers are for logging, not for hiding problems.