Hint
They crash Node.js 15+ β always attach .catch() or try/catch; use global handlers as last resort
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
});