🔧 Error Fixes
· 1 min read

UnhandledPromiseRejection — How to Fix It


UnhandledPromiseRejectionWarning: Error: something failed
UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block

A Promise rejected and nothing caught the error. In Node.js 15+, this crashes your process.

Fix 1: Add try/catch to async Functions

// ❌ No error handling
async function fetchData() {
    const res = await fetch('https://api.example.com/data');
    const data = await res.json();
    return data;
}

// ✅ Wrap in try/catch
async function fetchData() {
    try {
        const res = await fetch('https://api.example.com/data');
        const data = await res.json();
        return data;
    } catch (err) {
        console.error('Fetch failed:', err.message);
        return null;
    }
}

Fix 2: Add .catch() to Promises

// ❌ No .catch()
fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(data => console.log(data));

// ✅ Add .catch()
fetch('https://api.example.com/data')
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(err => console.error('Failed:', err));

Fix 3: Express Async Route Handler

// ❌ Express doesn't catch async errors by default
app.get('/api/data', async (req, res) => {
    const data = await fetchData();  // 💥 If this throws
    res.json(data);
});

// ✅ Wrap in try/catch
app.get('/api/data', async (req, res, next) => {
    try {
        const data = await fetchData();
        res.json(data);
    } catch (err) {
        next(err);
    }
});

Fix 4: Promise.all — One Failure Rejects All

// ❌ If any promise fails, all fail
await Promise.all([fetchA(), fetchB(), fetchC()]);

// ✅ Use Promise.allSettled to handle individual failures
const results = await Promise.allSettled([fetchA(), fetchB(), fetchC()]);
results.forEach(r => {
    if (r.status === 'rejected') console.error(r.reason);
});

Fix 5: Global Handler (Safety Net)

// Node.js — catch unhandled rejections globally
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled rejection:', reason);
    // Log it, but still fix the root cause
});