Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptUnhandle promise rejection in a basic catch block

Unhandle promise rejection in a basic catch block

In this article, we will try to analyze the case where promise rejection is left unhandled in the basic catch block itself with the output which will receive later on its execution, and further, we will try to analyze its solution through an example.

Let us first try to analyze the syntaxes which we will use for declaring a promise and a try-catch block in JavaScript during the error catching as well as handling process.

Syntax: The following syntax, we will use in order to declare a promise in JavaScript (either with the resolve() method or with the reject() method):

new Promise ((resolve, reject) => {
    // do something with either resolve() method....
    // or with reject() method...
})

Another shown below is  the syntax that we will use in order to declare a try-catch block in JavaScript for error catching as well as handling:

try {
    // do something...
    // error must be caught in this block itself...
}

catch(error_variable) {
    // do something with this error_variable...
}

After analyzing all the above-shown syntaxes let us analyze our problem statement with the help of an example that will also cover all the above-shown syntaxes (theoretically as well as with coding in JavaScript itself) shown below:

Example 1: 

  • In this example, we will first create a method that returns a promise of rejected state (through the reject() method) which has to be cached later. 
  • Then we will again a method using the async keyword and inside that method, we will create a simple try-catch block in order to store and catch the error thrown by the first function. 
  • Inside the try-block, we will create a variable and inside the variable, we will store the error by making use of await keyword and then we will use the console.log() method in order to output the result. 
  • Inside the catch block, instead of handling the error, we actually throw the error using the throw keyword, later we get a warning error in our output (as shown in the output section itself). 

Javascript




<script>
    let errorThrownFunction = () => {
        return new Promise((resolve, reject) => {
            reject("Connection Failed!!..");
        });
    };
  
    let errorHandlerMethod = async () => {
        try {
            let result = await errorThrownFunction();
            console.log(result);
        } catch (error) {
            throw new Error(error);
        }
    };
  
    errorHandlerMethod();
</script>


Output:

 

Now as we have visualized the output very well, we get to know that something wrong has been implemented in the catch block itself and that we have to correct it. Its correction is implemented in the below-enlightened example itself.

Example 2: 

  • In this example, we will try to implement two methods with the same name and signature as we have implemented in the previous example itself. 
  • The only change we will implement is the change in the catch block’s throw statement itself since here by throwing an error we are actually avoiding the handling process of an error, we are throwing it directly and not handling it. 
  • In the catch block, we will use the console.log() method in order to handle the caught error in the previous method and later we will see the error handled message instead of the warning error.

Javascript




<script>
    let errorThrownFunction = () => {
        return new Promise((resolve, reject) => {
            reject("Connection Failed!!..");
        });
    };
  
    let errorHandlerMethod = async () => {
        try {
            let result = await errorThrownFunction();
            console.log(result);
        } catch (error) {
            console.log(error);
        }
    };
  
    errorHandlerMethod();
</script>


Output:

Connection Failed!!..

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