0
0
NodejsDebug / FixBeginner · 4 min read

How to Handle Unhandled Rejection in Node.js: Simple Fixes

In Node.js, unhandled promise rejections happen when a promise fails but no error handler is attached. Use the process.on('unhandledRejection') event to catch these errors globally and add .catch() handlers to promises to handle errors properly.
🔍

Why This Happens

Unhandled promise rejections occur when a promise throws an error but no .catch() handler is attached to handle it. Node.js then warns you because the error might crash your app or cause unexpected behavior.

javascript
const promise = new Promise((resolve, reject) => {
  reject(new Error('Oops!'));
});

// No .catch() attached to handle rejection
Output
(node:12345) UnhandledPromiseRejectionWarning: Error: Oops! at ... (node:12345) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (node:12345) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process.
🔧

The Fix

Always attach a .catch() handler to promises to handle errors. Additionally, listen to the unhandledRejection event on process to catch any missed errors and log or handle them gracefully.

javascript
const promise = new Promise((resolve, reject) => {
  reject(new Error('Oops!'));
});

promise.catch(error => {
  console.error('Caught error:', error.message);
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
  // You can log the error or exit process if needed
});
Output
Caught error: Oops!
🛡️

Prevention

To avoid unhandled rejections, always add .catch() to promises or use try/catch inside async functions. Use linting tools like ESLint with rules that warn about missing promise error handling. Also, handle the unhandledRejection event to catch any unexpected errors and keep your app stable.

⚠️

Related Errors

Similar errors include uncaughtException, which happens when an error is thrown but not caught anywhere in synchronous code. Handle it with process.on('uncaughtException'). Also, beware of memory leaks caused by unhandled rejections piling up without proper cleanup.

Key Takeaways

Always attach .catch() handlers to promises to handle errors.
Use process.on('unhandledRejection') to catch missed promise errors globally.
Lint your code to warn about missing promise error handling.
Handle unhandledRejection to prevent your app from crashing unexpectedly.
Use try/catch inside async functions for clean error management.