Node.js Process unhandledPromiseRejection Event
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
Please Login to comment...