Open In App
Related Articles

Node.js Process unhandledPromiseRejection Event

Improve Article
Improve
Save Article
Save
Like Article
Like

The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine.

The unhandledRejection event is emitted whenever a promise rejection is not handled. NodeJS warns the console about UnhandledPromiseRejectionWarning and immediately terminates the process. The NodeJS process global has an unhandledRejection event. This event is fire when unhandledRejection occurs and no handler to handle it in the promise chain. 

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.
  • callbackfunction: It is the event handler of the event.

Return Type: The return type of this method is void.

Example 1: Basic example to register an unhandledRejection listener. 

index.js




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


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. 

index.js




// 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))


Run index.js file using the following command:

node index.js

Output:

Invalid password

Note: If you handle unhandledRejection with the listener or consumer function then the default warning to the console (the UnhandledPromiseRejectionWarning from the above examples) will not print to the console. 

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


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 03 Nov, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials