PromptHub
Node.js Intermediate 13 views

Unhandled Promise Rejection

A Promise was rejected but no error handler was attached to catch the rejection.

Explanation

Unhandled Promise Rejection occurs when a Promise is rejected (an async operation fails) but no .catch() handler or try-catch with await is used to handle the rejection. In older Node.js versions, this was a warning; in Node.js 15+, it terminates the process like an uncaught exception. This is a common source of silent failures in async code. The rejection reason (error) is lost if not properly caught, making debugging difficult.

Common Causes

  • Missing .catch() on Promise
  • Missing try-catch around await
  • Promise.all with one rejection
  • Async function throwing without handling
  • Third-party library returning unhandled Promise

Solution

Always add .catch() handlers to Promises or use try-catch with async/await. Use process.on('unhandledRejection', handler) as a last-resort safety net. Enable strict unhandled rejection warnings in development. Wrap async functions in try-catch blocks. Use Promise.allSettled() instead of Promise.all() if you need all results regardless of failures. Add error boundaries in React for component-level error handling. Use ESLint rules like no-floating-promises.

Code Example

// Unhandled rejection - no catch handler
fetch('/api/data')
    .then(res => res.json())
    .then(data => process(data)); // no catch!

// Fix: add catch handler
fetch('/api/data')
    .then(res => res.json())
    .then(data => process(data))
    .catch(err => console.error('Failed:', err));

// async/await with try-catch
async function loadData() {
    try {
        const res = await fetch('/api/data');
        const data = await res.json();
        return data;
    } catch (err) {
        console.error('Failed to load:', err);
        throw err;
    }
}

// Promise.all with individual handlers
const promises = [
    fetch('/api/a').catch(handleError),
    fetch('/api/b').catch(handleError),
];
const results = await Promise.all(promises);

// Global safety net (last resort)
process.on('unhandledRejection', (reason, promise) => {
    console.error('Unhandled Rejection:', reason);
});

Error Information

Language

javascript

Framework

nodejs

Difficulty

Intermediate

Views

13

Related Errors