Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to create a global Promise Rejection Handler in JavaScript ?

How to create a global Promise Rejection Handler in JavaScript ?

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("neveropen");
});


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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen 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!

RELATED ARTICLES

Most Popular

Recent Comments