🟒 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