How can I get a JavaScript stack trace when I throw an exception?


This tutorial teaches us to get a JavaScript stack trace when we throw an exception. Usually, the developer uses the stack trace to identify the errors while executing the program's code. However, we use the stack trace to debug the program.

Using the stack trace, we can get knowledge of any kind of exceptions, such as constructor error, naming error, etc., in our program, and we can correct them.

Before we approach analyzing the error using the stack trace, we should know how to stack trace works.

How does the call stack trace works?

The stack is the primary data structure that follows the LIFO (last in, first out) property. When we execute any program in our machine, the operating system allocates some dynamic memory to the program in either a stack or heap. In most cases, it allocates in the stack format as it is easy to manage.

For example, we have two functions named a child() and parent() as given below.

function child() {
   // code for child function
}
Function parent() {
   child();
   // code for parent function.
}
parent();

In the above snippet, when we start to execute the program, it gets the stack trace allocated by the operating system, and the parent() function goes to the stack trace. After that, the child() function will be called from the parent function. So, it goes to the top of the stack.

When the program's execution completes, the child() function will be removed first from the stack, and after that parent() function.

Now, users can think about the scenario where we don’t know which function is throwing an error. They can print the stack trace in any function, get knowledge about the error and solve it.

Below are different approaches to printing the stack trace in the JavaScript Program.

  • Using the Error Object Property
  • Using the console.trace() Method

Using the Error Object Property

In this approach, we will create a new error object for demonstration and return the error stack from the function. The error stack also prints the whole stack trace for the program according to the flow, and it contains all the function call from the program's start to the most recent execution.

Syntax

Users can follow the below syntax to get the error stack trace.

function() {
   // execution code for the function
   var error = new Error();
   return error.stack;
}

In the syntax, we have created the error using the constructor of the error class which is a new Error().

Example 1

The below example demonstrates that how stack trace is printed when we throw an error from the any function.

<!DOCTYPE html>
<html>
<body>
   <h2>The stack trace when we throw an exception.</h2>
   <p id="resultDiv"> </p>
   <script type="text/javascript">
      // this function contains error
      // it prints stack trace for all function from parent to getStrackTrace
      function getStackTrace() {
         var error = new Error();
         let resultDiv = document.getElementById("resultDiv");
         resultDiv.innerHTML = error.stack;
      }
      function child() {
         getStackTrace();
      }
      function parent() {
         child();
      }
      // call the parent function
      parent();
   </script>
</body>
</html>

In the above output, users can see that it shows the whole stack trace from the parent function to the getStackTrace() function which throws an error. Also, it shows line by line for every stack element which helps programmers to locate the error and find a better solution.

Using the console.trace() Method

In this approach, we will use the console.trace() method. It is a very straightforward method to print the stack trace of the program till the current line execution. Developers can call the method in a function or program, and it prints the stack trace, and users can debug the whole code.

Syntax

Users can follow the below syntax to use the console.trace() method.

function() {
   // function body
   // console.trace();
}

Example 2

The below example demonstrates how we can print the stack trace using the console.trace() method. It prints the output inside the console.

<!DOCTYPE html>
<html>
<body>
   <h2>The stack trace when we throw an exception. </h2>
   <p> Clicking "Trace" button calls startExecution function,
      which calls middleOfExecution and printStackTrace, printStackTrace fucntion calls console.trace(),
which displays the trace in the console.</p>
   <p>Remember to open the console before you click "Trace".</p>
   <button onclick="startExecution()">Trace</button>
   <script type="text/javascript">
      function printStackTrace(string) {
         // create new error and logging it by console.
         // var error = new Error();
         console.trace(string);
         return 10 * 20;
      }
      function middleOfExecution() {
         console.log(10 * 20);
         return 10 * 20;
      }

      // call the printStackTrace function inside this.
      function startExecution() {
         middleOfExecution();
         let string = "tutorialsPoint";
         printStackTrace(string);
         console.log(string);
      }
   </script>
</body>
</html>

In the above output, users can see how clearly console.trace() method prints the stack trace of the program execution.

Conclusion

We have seen two methods to get the stack trace when we throw an error. Users can use anyone according to their understanding. Generally, the second approach is used when working with the terminal or backend. Users can use the first approach to log the stack trace into the browser.

Updated on: 12-Jul-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements