Open In App

Node.js Process unhandledRejection Event

Last Updated : 22 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The process is the global object in Node.js that maintains track of and includes all of the information about the specific Node.js process that is running on the computer at the time. When a promise rejection is not handled, the unhandled rejection event is emitted. Node.js issues an UnhandledPromiseRejectionWarning to the terminal and promptly ends the process. The global Node.js process has an unhandled rejection event. This event is triggered when an unhandled rejection happens and there is no handler in the promise chain to handle it.

Syntax:

process.on("unhandledRejection", callbackfunction)

Parameters: This method takes the following two parameters.

  • unhandledRejection: It is the name of the emit event in the process.
  • Callback function: It is the event handler of the event.

Return Value: The return type of this method is void

Example 1: Basic example to register an unhandledRejection listener.

Javascript




// The unhandledRejection listener
process.on('unhandledRejection', error => {
    console.error('unhandledRejection', error);
});
  
// Reject a promise
Promise.reject('Invalid password');


Steps to run: Run index.js file using the following command:

node index.js

Output:

unhandledRejection Invalid password

Example 2: To demonstrate that the unhandledRejection listener will only execute when there is no promise rejection handler in your chain. 

Javascript




// The unhandledRejection listener
process.on('unhandledRejection', error => {
    // Won't execute
    console.error('unhandledRejection', error);
});
  
// Reject a promise
Promise.reject('Invalid password')
    .catch(err => console.error(err))


Steps to run: Run index.js file using the following command:

node index.js

Output:

Invalid password

Reference: https://nodejs.org/api/process.html#process_event_unhandledrejection


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads