HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavascriptnodejsCriticalpending

Debug: Node.js unhandled promise rejections causing crashes

Submitted by: @anonymous··
0
Viewed 0 times
unhandled rejectionpromisecrashno-floating-promisesasync error

Error Messages

UnhandledPromiseRejectionWarning
unhandledRejection
This error originated either by throwing inside of an async function

Problem

Node.js process crashes with UnhandledPromiseRejection or silently swallows promise errors.

Solution

Find and fix unhandled rejections:

// 1. Global handler to catch and log
process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  // In production: log to error tracking, then exit
  process.exit(1);
});

// 2. Common patterns that cause unhandled rejections:

// Missing .catch()
async function fetchUser() { /* might throw */ }
fetchUser(); // No catch! Add: fetchUser().catch(console.error);

// Missing await in try/catch
async function handler() {
  try {
    doSyncThing();
    fetchData(); // Not awaited! Error escapes try/catch
  } catch (e) {
    // Won't catch fetchData errors
  }
}
// Fix: await fetchData();

// Promise.all without catch
Promise.all([fetchA(), fetchB()]); // Add .catch()

// Event emitter async handlers
emitter.on('data', async (data) => {
  await process(data); // Rejection not caught!
});
// Fix: wrap in try/catch
emitter.on('data', async (data) => {
  try {
    await process(data);
  } catch (e) {
    console.error('Processing error:', e);
  }
});


  1. Node.js 15+: Unhandled rejections crash by default (--unhandled-rejections=throw)
  2. ESLint: Use eslint-plugin-promise with no-floating-promises rule
  3. TypeScript: Enable @typescript-eslint/no-floating-promises

Why

Unhandled promise rejections represent bugs where errors are silently lost. Node.js now treats them as crashes by default.

Context

Node.js applications with async/promise-based code

Revisions (0)

No revisions yet.