Open In App

JavaScript/TypeScript: Standard way to keep the cause of an Error

In this article, we will try to understand that what’s the standard way to keep the cause of an Error in JavaScript (or in TypeScript) with the help of certain coding examples.

Since there is no such provision provided in JavaScript/TypeScript where directly we may be able to find out the cause of an error (like no such property or in-built method exists in either of the languages), therefore we have to manually do some changes while throwing some errors one after the other.



We will understand our problem statement with the help of an example shown below.

Example 1:






<script>
    let errorFunction = () => {
        try {
            try {
                throw new Error(
                    "Second Error: Something went wrong..!!");
            } catch (error2) {
                console.log(error2);
                throw new Error("First Error: Error 404!!...");
            }
        } catch (error1) {
            console.log("-------------------------");
            console.log(error1);
        }
    };
  
    errorFunction();
</script>

Output:

 

Now, as we may visualize in the browser’s console’s output the first error doesn’t keep any reference to the second error so that is actually our problem statement which we will solve in another example shown below.

Example 2:




<script>
    let errorFunction = () => {
        try {
            try {
                throw new Error(
                    "Second Error: Something went wrong..!!");
            } catch (error2) {
                console.log(error2);
                throw new TrackError(
                    "First Error: Error 404!!...", error2);
            }
        } catch (error1) {
            console.log("-------------------------");
            console.log(error1);
        }
    };
    errorFunction();
</script>

Output:

 


Article Tags :