How to Fix Unhandled Promise Rejection in JavaScript
In this tutorial, you'll learn about How to Fix Unhandled Promise Rejection in JavaScript. We cover key concepts, practical examples, and best practices.
The Problem
An unhandled promise rejection occurs when a Promise is rejected and no .catch() handler or try/catch block is attached to handle the error, causing Node.js to log warnings or crash in future versions.
Quick Fix
Step 1: Add a .catch() handler
Every promise chain should end with a catch:
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data));
If the fetch fails, the rejection is unhandled. Add .catch():
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error('Request failed:', err.message));
Request failed: Failed to fetch
Step 2: Use async/await with try/catch
Async functions without wrapping are also vulnerable:
async function load() {
const data = await fetch('/api/data');
}
load();
If the fetch rejects, the rejection is unhandled because the caller does not handle it:
async function load() {
try {
const data = await fetch('/api/data');
console.log(data);
} catch (err) {
console.error('Load failed:', err.message);
}
}
load();
Step 3: Attach catch to individual promises in Promise.all
A rejection in Promise.all becomes a single rejection:
Promise.all([
fetch('/api/a'),
fetch('/api/b')
]).then(([a, b]) => console.log(a, b));
Handle the combined promise:
Promise.all([
fetch('/api/a'),
fetch('/api/b')
])
.then(([a, b]) => console.log(a, b))
.catch(err => console.error('One of the requests failed:', err.message));
Step 4: Register a global handler for remaining rejections
In Node.js (required before process exit in Node 15+):
process.on('unhandledRejection', (reason) => {
console.error('Unhandled Rejection:', reason);
});
In browsers:
window.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled Rejection:', event.reason);
event.preventDefault();
});
Prevention
- Always terminate promise chains with
.catch(). - Use async/await with try/catch instead of raw
.then()chains. - Register a global unhandled rejection handler.
- Use lint rules like ESLint
no-unused-promisesto catch missing handlers.
Common Mistakes with promise unhandled
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro