Print the Function Call Flow with Stack Trace in JavaScript

Hey, friends today you will learn How to Print the Function Call Flow with Stack Trace in JavaScript. Learn how to Print the Stack Trace and the function call flow of your JavaScript and Google Apps Script programs.

Java’s printStackTrace function is important for handling exceptions and failures when developing. It indicates the exact line number in your source code as well as the file name where the error occurred.

If you’re working with JavaScript or Google Apps Script, you can use the console.trace() method to display the entire stack in the browser console ( or StackDriver logs for Google Scripts).

A better solution is to parse the Error object’s stack attribute. This includes the whole stack trace, as well as line numbers, column positions, and function names.

function printStackTrace() {
  const error = new Error();
  const stack = error.stack
    .split("\n")
    .slice(2)
    .map((line) => line.replace(/\s+at\s+/, ""))
    .join("\n");
  console.log(stack);
}

function three() {
  console.log("Function Three!");
  printStackTrace();
}

function two() {
  console.log("Function Two!");
  three();
}

function one() {
  console.log("Function One!");
  two();
}

one();

The printStackTrace function returns something like this. The first few lines are the output of the programme, and as you scroll down, you’ll notice a list of methods that invoked the previous method.

Also, see: Add Options in Google Forms Questions from Google Sheets

Function One!
index.js:16 Function Two!
index.js:11 Function Three!
index.js:7 three (index.js:12:3)
two (index.js:17:3)
one (index.js:22:3)
index.js:26:3
index.js:27:3

You can use the stack trace to determine the precise location of the broken code in your JavaScript app or to just print the function calling flow of your JavaScript application without throwing an exception.

Also, see: How to Find Google Sheets Linked to your Google Forms

Leave a Comment