EasyAsync JS📖 Theory Question

How do you handle unhandled Promise rejections?

💡

Hint

They crash Node.js 15+ — always attach .catch() or try/catch; use global handlers as last resort

Full Answer

An unhandled rejection occurs when a Promise rejects with no .catch() or try/catch handler.

// ❌ Unhandled
const p = Promise.reject(new Error('oops'));
// Browser: warning in console; Node.js 15+: crashes process

// ✅ Always handle
async function fetchData() {
  try {
    return await fetch('/api');
  } catch (err) {
    if (err.status === 404) return null; // handle known
    throw err;                           // re-throw unknown
  }
}

// ✅ At call site
fetchData().catch(err => console.error(err));

// Global handlers (last resort / monitoring)
// Browser
window.addEventListener('unhandledrejection', (event) => {
  console.error('Unhandled:', event.reason);
  event.preventDefault(); // suppress browser logging
});

// Node.js
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection:', reason);
  process.exit(1); // recommended in production
});
💡 Never rely on global handlers for correctness — they're for logging/monitoring. Fix the root cause by ensuring every async operation is wrapped in try/catch or has .catch().

More Async JS Questions

EasyExplain Promises — states, chaining, and error handling.EasyHow does async/await work under the hood?EasyWhat is callback hell and how do you avoid it?EasyWhat are Promise combinators and when do you use each?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint