UnhandledPromiseRejectionWarning: Error: something went wrong
A Promise rejected and nothing caught the error.
Fix 1: Add .catch()
// ❌ No error handling
fetch('/api/data').then(res => res.json());
// ✅ Handle errors
fetch('/api/data')
.then(res => res.json())
.catch(err => console.error('Failed:', err));
Fix 2: Use try/catch with async/await
// ❌ No try/catch
async function getData() {
const res = await fetch('/api/data');
return res.json();
}
// ✅ Wrap in try/catch
async function getData() {
try {
const res = await fetch('/api/data');
return await res.json();
} catch (err) {
console.error('Failed:', err);
}
}
Fix 3: Global handler (for debugging)
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection:', reason);
});