Course contentsShow
← JavaScript
Lesson 1506 of 2,72333. JavaScript in Node.jsFree lesson

Process Event: 'unhandledRejection'

Detecting unhandled promise rejections to prevent silent failures in async code.

Process Event: 'unhandledRejection'

You'll learn how to catch unhandled promise rejections in Node.js before they silently crash your application.

What Are Unhandled Rejections?

When a promise rejects and you don't attach a .catch() handler or use try/catch with await, that rejection goes "unhandled." In modern Node.js versions, unhandled rejections can terminate your entire process—but the 'unhandledRejection' event gives you a safety net to detect and log these issues before they become invisible bugs.

Why This Matters

Imagine you have async code scattered throughout your application. If one promise rejection slips through without a handler, it could fail silently in production. The 'unhandledRejection' event acts like a last-resort alarm system, alerting you to promises that rejected without anyone listening.

Listening for Unhandled Rejections

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection detected!');
  console.error('Reason:', reason);
  console.error('Promise:', promise);
  // Log to monitoring service, gracefully shut down, etc.
  process.exit(1);
});

// This will trigger the event:
Promise.reject(new Error('Oops, forgot to handle this'));

// This WON'T trigger it (handled):
Promise.reject(new Error('Handled')).catch(err => console.error(err));

The event receives two arguments: the rejection reason (often an error) and the promise that rejected.

Common Use Cases

  • Production monitoring: Log unhandled rejections to error tracking services
  • Graceful shutdown: Clean up resources before exiting
  • Development debugging: Catch mistakes where you forgot error handling

Key Takeaway: Listen for 'unhandledRejection' to prevent silent promise failures from crashing your Node.js application unexpectedly—it's your safety net for async error handling gaps.