Open In App

How to create a global Promise Rejection Handler in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will try to understand firstly how we create a Rejected Promise, and later we will see how we may create a Global Promise Rejection Handler which will try to handle (somehow) that Rejected Promise created earlier in JavaScript.

Let us first try to understand how we create a Promise (with Rejected State) in JavaScript using the following enlightened syntax:

Syntax:

new Promise ((resolve, reject) => {
    reject ("Some rejection message....")
})

Now let us have a look over the following shown example which will create a rejected promise using the above-shown syntax:

Example 1: In this example, we will try to create a rejected promise that will try to output some result (which is obviously the rejected message itself).

Javascript




let new_rejected_promise = new Promise((resolve, reject) => {
    reject("Something went wrong!!!....");
});
  
console.log(new_rejected_promise);


Output:

 

Since in this code, we haven’t handled the rejected promise and that’s the only reason we will get this type of output in the browser’s console and is high time we should have a look over the below-shown example that will help us to create a Global Promise Rejection Handler in JavaScript.

Example 2: In this example, we will try to create a global promise rejection handler (in the form of a method), and in that method we will assign it to a new window object’s property called window.onunhandledrejection. Using this property we will be able to catch all the rejected promises messages at once only if we haven’t used the catch() method for the same.

Javascript




let RejectionHandlerGlobally = (event) => {
    console.log("Promise Rejection reason: ", event.reason);
};
  
window.onunhandledrejection = RejectionHandlerGlobally;
  
let new_promise = new Promise((resolve, reject) => {
    reject("Something went wrong!!...");
});
  
new_promise.then(() => {
    console.log("GeeksforGeeks");
});


Output:

 

Note: Although in the above code we have provided the global promise rejection handler method, still in output we experience an error message (shown in red color itself), that’s why it is highly recommended that we should always use the catch() method wherever possible.



Last Updated : 17 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads