Open In App

How to escape try/catch hell in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

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("GeeksforGeeks...");
            }, 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: GeeksforGeeks...

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("GeeksforGeeks...");
            }, 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: GeeksforGeeks...

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("GeeksforGeeks...");
            }, 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: GeeksforGeeks...


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