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
- Handle local rejections:
promise.then(...).catch(err => console.error(err));. - Wrap async/await:
try { await task(); } catch (err) { ... }. - Add a global safety net:
process.on('unhandledRejection', (reason, promise) => { ... });. - In Express, use async error wrappers so rejected promises reach your error middleware.
- Consider using a library like
p-retryfor 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.
unhandledRejectiondoes not catch rejections that occur after the initial tick if a catch is attached later.