How-To Guide

How to Handle Unhandled Promise Rejections

Stop unhandled rejections from crashing or hiding: attach handlers, catch at the boundary, avoid fire-and-forget, and monitor the global hook.

On this page

  1. Introduction
  2. Attach a handler to every rejecting promise
  3. Avoid fire-and-forget
  4. Catch at the request boundary
  5. Use the global hook as a net, not the strategy
  6. Test that rejections are handled
  7. Common pitfalls
  8. Conclusion

Introduction

A promise that rejects without a handler is an error nobody saw. In older runtimes it was ignored silently; in current Node it is a fatal error that exits the process, because a silent failure corrupts state and hides bugs. Both behaviors are bad: the ignored rejection loses the error, and the crash takes down the service for one missed catch. The real fix is to handle rejections where they occur and to keep a global hook as a net, not as the strategy.

This tutorial covers attaching handlers, avoiding fire-and-forget, catching at the request boundary, and using the global hook for observability. The examples use Node.js and async functions, and the discipline applies to any promise-based runtime.

Attach a handler to every rejecting promise

Every promise that can reject needs a handler: an await inside a try, a .catch on the chain, or a returning of the promise to a caller that handles it. A promise created and not handled is where the unhandled rejection comes from. Go through the async calls and ensure each has a path for its rejection, even if the path is to log and continue.

A common source is a helper that returns a promise which the caller then awaits, but the caller is not always the one who creates it. Be explicit: if a function returns a promise, its caller must handle it. A promise left dangling inside a .then callback or a setTimeout is the hidden case, because it looks handled by the surrounding code but is not.

// unhandled: the rejection has no handler
async function load() { throw new Error('boom'); }
setTimeout(() => { load(); }, 10);   // rejection goes nowhere

// handled: the rejection has a defined consequence
setTimeout(() => { load().catch((e) => logger.error(e)); }, 10);

Avoid fire-and-forget

Starting an async operation and dropping its promise is the most common cause. A handler calls an async function to send an email or update a cache, does not await it, and does not handle its rejection. The operation runs, fails, and the rejection is unhandled. If the work must run in the background, handle it explicitly: await it where the caller can afford to, or attach a handler that records the failure.

For genuinely background work, make the fire-and-forget explicit with a wrapper that always attaches a handler, so a failure is logged and metered rather than unhandled. Never leave a bare async call. The wrapper documents that this is intentional background work and gives its failure a home.

function background(name: string, fn: () => Promise<unknown>) {
  fn().catch((err) => {
    logger.error({ err, task: name }, 'background task failed');
    metrics.incr('background.failure');   // the failure has a consequence
  });
}

background('send-email', () => sendEmail(user));   // explicit, handled

Catch at the request boundary

An async request handler that rejects can leave the client hanging with no response, because nothing turns the rejection into a response. Wrap the handler so any rejection becomes an error response, and so the rejection does not propagate to the global hook. This is the boundary where handling has a clear consequence: send a 500 and log the details.

A single wrapper around the handler means every route is covered, rather than each handler needing its own try. In a framework, an async error-handling middleware or a wrapper function does this. The wrapper catches, maps the error to a status, and logs it with the request context, so the failure is both reported to the client and visible to the operator.

function asyncHandler(fn) {
  return (req, res, next) => {
    Promise.resolve(fn(req, res, next)).catch(next);   // to the error middleware
  };
}

app.get('/orders', asyncHandler(async (req, res) => {
  const orders = await loadOrders();   // a rejection goes to the error middleware
  res.json(orders);
}));

Use the global hook as a net, not the strategy

Install the unhandled-rejection hook to log and alert on any rejection that reached it. It is the last line: a rejection there means a handler was missing, which is a bug to fix. The hook should log the error and increment a metric, so the gap is visible, and then let the default behavior proceed or exit deliberately, depending on whether the process can continue safely.

Do not use the hook as the primary handling or to swallow errors silently. A process that logs and continues after an unhandled rejection may be in an inconsistent state, because the rejection happened at an unknown point. Where correctness matters, an unhandled rejection is best treated as fatal, with the hook capturing the details before the exit, and the fix being to handle the rejection at its source.

process.on('unhandledRejection', (reason) => {
  logger.error({ err: reason }, 'unhandled rejection');   // visible in logs and alerts
  metrics.incr('unhandled_rejection');
  // then either exit or continue, per your correctness requirements
});

Test that rejections are handled

Write a test that starts an operation whose promise rejects and asserts the rejection is observed, by a stub that records a handled flag. Test that a request handler whose dependency rejects returns a 500 rather than hanging, which proves the boundary wrapper. Test that background work failure increments the failure metric, proving the wrapper handles it. Assert the global hook is not triggered in normal failure paths, because a trigger means a missing handler.

node -e '
let handled = false;
const p = Promise.reject(new Error("x"));
p.catch(() => { handled = true; });
setTimeout(() => console.log("handled:", handled), 10);   // must be true
'

Common pitfalls

Starting an async operation without a handler, a promise inside a .then that is not returned, awaiting in some paths but not others, using the global hook to swallow the error, and relying on a crash as the handling are the recurring mistakes. A handler on every rejecting promise, an explicit background wrapper, a boundary catch, a global hook for visibility, and a test that rejections are observed address them.

Conclusion

An unhandled rejection is an error nobody saw, and the fix is to handle it where it happens. Attach a handler to every rejecting promise, make background work explicit with a wrapper, catch at the request boundary so a failure becomes a response, and keep the global hook as a net that logs and alerts. Self-check by asserting every started operation is handled and that the global hook stays quiet on normal failures. Then a rejection has a consequence instead of a crash or a silence.

Sources: Node.js: Unhandled promise rejections, MDN: Promise.prototype.catch, MDN: try…catch with await.

FAQ

Why did my Node process exit on an unhandled rejection?
Modern Node versions treat an unhandled rejection as a fatal error by default, because a silently ignored failure is worse than a crash. The fix is not to disable the behavior but to handle the rejection at its source or at the boundary.
Is a global handler enough?
No. A global handler catches what slipped through, but a rejection reaching it means a handler was missing somewhere. Log it and alert, but fix the site so the rejection is handled where the operation is started and its failure has a defined consequence.

Related Examples