0
0
Node.jsframework~5 mins

Unhandled rejection handling in Node.js

Choose your learning style9 modes available
Introduction

Unhandled promise rejections happen when a promise fails but no code catches the error. Handling them helps keep your program stable and avoid crashes.

When you want to catch errors from promises that were not handled anywhere else.
When you want to log or report unexpected errors in asynchronous code.
When you want to prevent your Node.js app from crashing due to unhandled promise errors.
When debugging to find where promises fail without proper error handling.
When you want to clean up resources or shut down gracefully on unexpected errors.
Syntax
Node.js
process.on('unhandledRejection', (reason, promise) => {
  // handle the error here
});

This listens for any promise rejection that was not caught.

The reason is the error or value that caused the rejection.

Examples
Logs the error reason when an unhandled rejection happens.
Node.js
process.on('unhandledRejection', (reason, promise) => {
  console.log('Unhandled rejection:', reason);
});
Logs the error and then stops the Node.js process to avoid unstable state.
Node.js
process.on('unhandledRejection', (reason, promise) => {
  // Exit the process after logging
  console.error('Error:', reason);
  process.exit(1);
});
Sample Program

This program listens for unhandled promise rejections and logs the error message. The promise rejects without a catch, so the handler runs.

Node.js
process.on('unhandledRejection', (reason, promise) => {
  console.log('Caught unhandled rejection:', reason.message);
});

// Create a promise that rejects but has no catch
new Promise((resolve, reject) => {
  reject(new Error('Oops!'));
});
OutputSuccess
Important Notes

Always try to handle promise errors with .catch() or try/catch in async functions.

Use unhandled rejection handling as a safety net, not a replacement for proper error handling.

In Node.js 15+, unhandled rejections may cause the process to exit by default, so handling them is important.

Summary

Unhandled rejection handling catches errors from promises that no one caught.

It helps keep your app stable and lets you log or clean up on errors.

Use process.on('unhandledRejection') to listen and respond to these errors.