How to handle promise rejections in Node.js

· Category: Node.js

Short answer

Always attach .catch() handlers to promises and wrap await calls in try/catch blocks. For global safety, listen to unhandledRejection events.

Steps

  1. Handle local rejections: promise.then(...).catch(err => console.error(err));.
  2. Wrap async/await: try { await task(); } catch (err) { ... }.
  3. Add a global safety net: process.on('unhandledRejection', (reason, promise) => { ... });.
  4. In Express, use async error wrappers so rejected promises reach your error middleware.
  5. Consider using a library like p-retry for transient failures.

Tips

  • In modern Node.js versions, unhandled rejections can terminate the process; do not rely solely on global handlers.
  • Log the stack trace and context of rejections to make debugging easier.

Common issues

  • Floating promises without await or .catch() are a frequent source of silent failures.
  • unhandledRejection does not catch rejections that occur after the initial tick if a catch is attached later.