What is an onunhandledrejection in javascript?

The onunhandledrejection is an event handler to process unhandledrejection events that occur whenever a Promise rejection is not handled. Before going deep into onunhandledrejection, let’s learn about Promise rejection.

The Promise rejection

Promise is an object of JavaScript, which is responsible for handling asynchronous events for either a completed state or a rejected state, which are called resolve and reject, respectively. Initially, it possesses a pending state, then goes to a completion or rejection state, depending on the outcome.

States of Promise
States of Promise

Code example

The method reject(reason) of the Promise object is used to return the rejected Promise with a reason for the rejection in parameters.

Look at the below code:

// Rejecting the promise with a reason
var promise = Promise.reject("Oops! I am rejected");
promise.then(() => {
console.log("Hello World");
});

Code explanation

In the above code, the promise.then() function deals with the asynchronous calls in JavaScript. The Promise object is rejected with the reason "Oops! I am rejected" but there is nothing to catch this rejection, so this is an unhandled rejection. It will directly go to the console, and an error message will be shown like this:

(node:22) UnhandledPromiseRejectionWarning: Oops! I am rejected

and

(node:22) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

These errors show that an unhandled promise rejection is thrown by the code and not caught.

Note: A depreciation warning (node:21) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. will also be displayed because unhandled promise rejections are deprecated now.

Now, we will use the onunhandledrejection event handler to catch the rejection thrown.

The onunhandledrejection event handler

To catch the error gracefully and show it on the console, we can use a different method like catch or onunhandledrejection, but here, we are going to catch the Promise rejection using the globally available onunhandledrejection property from the window object. This is useful for debugging and error handling for unexpected cases.

Code Example

Console
Error handling by onunhandledrejection

Code explanation

In the above code, we have added window.onunhandledrejection with a message. This will catch the rejection thrown by Promise.reject() and display the message gracefully. The following output will be shown:

Output
Output

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved