How to handle unhandled promise rejections in JavaScript
· Category: JavaScript
Short answer
Unhandled promise rejections occur when a Promise rejects without a catch handler. Always attach .catch() or use try/catch with await to handle them.
Steps
- Attach a catch handler:
javascript fetch("/api").then(r => r.json()).catch(err => console.error(err)); - Use try/catch with await:
javascript try { const data = await fetchData(); } catch (err) { console.error(err); } - Listen for global unhandled rejections:
javascript window.addEventListener("unhandledrejection", event => { console.error("Unhandled:", event.reason); event.preventDefault(); }); - Handle rejections in Promise.all:
javascript Promise.all(tasks).catch(err => console.error(err));
Tips
- In Node.js, unhandled rejections may terminate the process in future versions.
- Log unhandled rejections to your error tracking service.
Common issues
- Forgetting to return a Promise inside a
.then()chain leaves rejection unhandled. - Async functions that throw without a caller catch block result in unhandled rejections.