In this article, we will try to understand how we may escape from multiple try/catch hell (that is multiple sequences of occurrences of try/catch blocks) in JavaScript.
Let us first quickly visualize how we may create a try/catch block in JavaScript using the following illustrated syntax:
Syntax: Following is the simple syntax that we may use to create a particular simple try/catch block inside any function or a method:
try {
// do something...
}
catch(errorMessage){
// do something...
}
Now, let us see the following syntax which describes how we may have try/catch hell (means multiple try/catch blocks for accessing multiple values):
Syntax:
try {
// do something...
}
catch(error){
// do something...
}
try {
// do something...
}
catch(error){
// do something...
}
...
Let us have a look over the below-mentioned example which will help us to understand the above-mentioned syntax of try/catch and also will try to see what is try/catch blocks hell syntax which is described above as a syntax.
Example 1: In this example, we will try to understand the syntax of try/catch block and will further see how we may create a try/catch blocks hell (that is multiple sequences of try/catch blocks hell).
Javascript
<script>     function nameOfEmployee() {         let name_of_person = new Promise((resolve, reject) => {             setTimeout(() => {                 resolve("Johnson...");             }, 1000);         });         return name_of_person;     }       function nameOfOrganization() {         let name_of_organization =             new Promise((resolve, reject) => {             setTimeout(() => {                 resolve("neveropen...");             }, 2000);         });         return name_of_organization;     }       async function displayData() {           // Here comes the try/catch blocks hell...         // First try/catch block...           try {             let name = await nameOfEmployee();             console.log("Name of an employee is: " + name);         } catch (error) {             console.log(error);         }           // Second try/catch block...         try {             let organization = await nameOfOrganization();             console.log("Name of an organization is: "                 + organization);         } catch (err) {             console.log(err);         }                   // As per need more number of try/catch         // blocks may be added...     }       displayData(); </script> |
Output:
Name of an employee is: Johnson... Name of an organization is: neveropen...
As we have seen in the above-mentioned example, the try/catch hell for just achieving multiple values in different functions that we have created multiple try/catch blocks which actually becomes a hell. Let us now see how we may avoid unnecessary try/catch block sequences using the below-illustrated example.
Example 2: This example is the extension of the previous example, where we have seen how we may create a try/catch hell and in this, we will avoid using multiple unnecessary try/catch blocks.
Javascript
<script> Â Â Â Â function nameOfEmployee() { Â Â Â Â Â Â Â Â let name_of_person =Â Â Â Â Â Â Â Â Â Â Â Â Â new Promise((resolve, reject) => { Â Â Â Â Â Â Â Â Â Â Â Â setTimeout(() => { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â resolve("Johnson..."); Â Â Â Â Â Â Â Â Â Â Â Â }, 1000); Â Â Â Â Â Â Â Â }); Â Â Â Â Â Â Â Â return name_of_person; Â Â Â Â } Â Â Â Â Â Â function nameOfOrganization() { Â Â Â Â Â Â Â Â let name_of_organization =Â Â Â Â Â Â Â Â Â Â Â Â Â new Promise((resolve, reject) => { Â Â Â Â Â Â Â Â Â Â Â Â setTimeout(() => { Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â resolve("neveropen..."); Â Â Â Â Â Â Â Â Â Â Â Â }, 2000); Â Â Â Â Â Â Â Â }); Â Â Â Â Â Â Â Â return name_of_organization; Â Â Â Â } Â Â Â Â Â Â async function displayData() { Â Â Â Â Â Â Â Â let name = await nameOfEmployee() Â Â Â Â Â Â Â Â Â Â Â Â .catch((error) => console.log(error)); Â Â Â Â Â Â Â Â let organization = await nameOfOrganization() Â Â Â Â Â Â Â Â Â Â Â Â .catch((error) => console.log(error)); Â Â Â Â Â Â Â Â console.log("Name of an employee is: " + name); Â Â Â Â Â Â Â Â console.log("Name of an employee is: " + organization); Â Â Â Â } Â Â Â Â Â Â displayData(); </script> |
Output:
Name of an employee is: Johnson... Name of an organization is: neveropen...
The above-illustrated example would be the best approach to avoid multiple try/catch blocks hell, but still, it’s getting repetitive. So there is another approach (in the form of an example illustrated below) in which we will create a function or method that is completely responsible for handling all the errors.
Example 3: In this example, we will create a standardized function or a method that will be used to handle all the errors and results which is coming to it in the form of a promise. This example will illustrate the avoidance of try/catch hell (that is usage of multiple try-catch blocks for just fetching different information in several different functions).
Javascript
<script>     function nameOfEmployee() {         let name_of_person =             new Promise((resolve, reject) => {             setTimeout(() => {                 resolve("Johnson...");             }, 1000);         });         return name_of_person;     }       function nameOfOrganization() {         let name_of_organization =             new Promise((resolve, reject) => {             setTimeout(() => {                 resolve("neveropen...");             }, 2000);         });         return name_of_organization;     }       async function errorHandler(promise) {         try {             let data = await promise();             return [data, null];         } catch (error) {             return [null, error];         }     }       async function displayData() {         let [name, nameError] = await             errorHandler(nameOfEmployee);         let [organization, organizationError]             = await errorHandler(nameOfOrganization);           if (nameError) {             console.log(nameError);         } else {             console.log("Name of an employee is: " + name);         }           if (organizationError) {             console.log(organizationError);         } else {             console.log("Name of an organization is: "                 + organization);         }     }     displayData(); </script> |
Output:
Name of an employee is: Johnson... Name of an organization is: neveropen...
