How to escape try/catch hell in JavaScript ?
Last Updated :
15 Jun, 2022
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...
Similar Reads
How to Handle Errors in JavaScript?
In JavaScript Error Handling is used to find the errors in the code so, that the coder can find the particular issue to resolve it. Here are the different approaches to handle errors in JavaScript1. Using try catch and finally statementThe try, catch, and finally blocks are used for error handling.
4 min read
How to Catch JSON Parse Error in JavaScript ?
JSON (JavaScript Object Notation) is a popular data interchange format used extensively in web development for transmitting data between a server and a client. When working with JSON data in JavaScript, it's common to parse JSON strings into JavaScript objects using the JSON.parse() method. However,
1 min read
How to create custom errors in JavaScript ?
In this article, we will learn to create custom errors with some examples. Errors represent the state of being wrong in condition. Javascript handles a predefined set of errors by itself but if you want to create your own error handling mechanism you can do that with custom errors functionality avai
2 min read
How to check whether an object exists in javascript ?
Checking whether an object exists in JavaScript refers to determining if a variable or property has been declared and contains a valid value. This helps avoid errors when accessing or manipulating objects that may be undefined, null, or not initialized properly.Here we have some common approaches to
3 min read
JavaScript - How to Handle Errors in Promise.all?
To handle errors in Promise.all(), you need to understand that it fails immediately if any of the promises reject, discarding all resolved values. This behavior can lead to incomplete operations and potential application crashes. The best way to manage errors in Promise.all() is by using .catch() in
3 min read
How to use goto in Javascript ?
There is no goto keyword in javascript. The reason being it provides a way to branch in an arbitrary and unstructured manner. This might make a goto statement hard to understand and maintain. But there are still other ways to get the desired result. The method for getting the goto result in JavaScri
3 min read
JavaScript - Escape a String
These are the following ways to Escape a String in JavaScript:1. Using BackslashesThe most straightforward way to escape characters is by using backslashes (\). This method allows you to include special characters like quotes (" or '), backslashes, and control characters within a string.JavaScriptle
1 min read
JavaScript Errors Throw and Try to Catch
JavaScript uses throw to create custom errors and try...catch to handle them, preventing the program from crashing. The finally block ensures that code runs after error handling, regardless of success or failure.throw: Used to create custom errors and stop code execution.try...catch: Allows you to c
3 min read
How to stop forEach() method in JavaScript ?
Stopping a forEach() loop seems almost like an impossible task but here are a few tricks by which we might do it. Sample example using forEach(): var sum = 0; var number = [90, 4, 22, 48]; number.forEach(myFunction); function myFunction(item) { sum += item; } console.log(sum); Tricks to stop forEach
2 min read
How to Prevent XSS Attacks in JavaScript?
Cross-site scripting (XSS) is a security vulnerability that enables attackers to inject malicious scripts into web pages viewed by users, potentially leading to serious consequences such as data theft and unauthorized actions. Given that JavaScript is a fundamental technology in web development, it
4 min read