A Safety Net for Forgotten Errors

If a Promise is rejected and you forgot to attach a .catch() handler, the error won't just silently disappear. The browser generates a special global event: unhandledrejection.

window.addEventListener('unhandledrejection', function(event) {
  // The event has two key properties:
  console.log('Unhandled promise:', event.promise);
  console.error('Rejection reason:', event.reason);

  // Optionally: prevent the browser from printing it to the console
  // event.preventDefault();
});

Why This Matters in Production

Real-world applications use this event as a global error reporter. When a user experiences an unhandled rejection, this event fires and the application automatically sends a crash report to a service like Sentry or Datadog. This lets developers know something broke in production, even if they never personally saw the bug.

window.addEventListener('unhandledrejection', function(event) {
  sendToErrorTracker({
    message: event.reason.message,
    stack: event.reason.stack,
    timestamp: new Date().toISOString()
  });
});
Caution

The appearance of unhandledrejection events is a sign of incomplete error handling in your code. Treat them as real bugs. Always handle errors where they can occur — don't rely on this global handler as your primary error strategy.