How to Get Stack Trace in JavaScript

Habdul Hazeez Feb 02, 2024
  1. Get Stack Trace With the Error Object in JavaScript
  2. Get Stack Trace With Console.trace() in JavaScript
  3. Get Stack Trace With a Custom Function in JavaScript
  4. Get Stack Trace With StackTrace.js in JavaScript
How to Get Stack Trace in JavaScript

This article teaches you how to get a stack trace in JavaScript using the following ways:

  1. Get stack trace with the error object
  2. Get stack trace with console.trace()
  3. Get stack trace with a custom function
  4. Get stack trace with StackTrace.js

Get Stack Trace With the Error Object in JavaScript

Using the stack property in the JavaScript error object, you can get a stack trace. However, you’ll need to create the error object using the Error constructor.

Therefore, when an error occurs in your code, you create the error object. As a result, you can print the stack trace.

For example, we have the function add_num in our code below, which will add two numbers. Meanwhile, add_num has a conditional check that verifies the function arguments as numbers.

So, if the check fails, we create an error object from the Error constructor. Then, we print the stack trace using the stack property.

Therefore, we supplied a string as the second argument of the add_num function as a test. So, we get a stack trace when we execute the code.

Example code:

function add_num(first_number, second_number) {
  if (typeof (first_number) !== 'number' ||
      typeof (second_number) !== 'number') {
    var error = new Error();
    console.log(error.stack);
  } else {
    console.log(first_number + second_number);
  }
}

let a = 23;
let b = '23';

add_num(a, b);

Output:

add_num@http://localhost/stacktrace/stacktrace-1.html:11:17
@http://localhost/stacktrace/stacktrace-1.html:21:10
stacktrace-1.html:12:13

What’s more, you can also wrap your code in a try-catch block. So, you’ll place the code that can cause an error in the try block, and you get the stack trace from the catch block.

When an error occurs in the try block, you can access an exception variable. This exception variable has the stack property.

Example code:

try {
  let a = 23;
  console.log(a - b); /* Variable b is not defined, so we get an error */
} catch (e) {
  console.log(e.stack)
}

Output:

@http://localhost/stacktrace/stacktrace-1.html:11:4
stacktrace-1.html:13:12

Get Stack Trace With Console.trace() in JavaScript

The console object contains a trace() function to print a stack trace to the web console. So, you can place console.trace() in a section of code where an error has occurred.

Our example below is the add_num function discussed earlier. However, we’ve modified it to use the console.trace() function.

Therefore, you can call the add_num function with an invalid argument to print the stack trace. An invalid argument is a string because the add_num function only allows numbers; anything else causes an error.

Example code:

function add_num(first_number, second_number) {
  if (typeof (first_number) !== 'number' ||
      typeof (second_number) !== 'number') {
    console.trace();
  } else {
    console.log(first_number + second_number);
  }
}

let a = 23;
let b = '23';

add_num(a, b);

Output:

console.trace() stacktrace-2.html:11:13
    add_num http://localhost/stacktrace/stacktrace-2.html:11
    <anonymous> http://localhost/stacktrace/stacktrace-2.html:20

Meanwhile, you are not limited to using console.trace() when an error occurs. This means you can use it to print code execution.

So, in our example below, we use console.trace() to trace different execution of add_num.

Example code:

function add_numbers(a, b) {
  console.trace('You called add_numbers with', a, 'and', b);
  return a + b;
}

function calculate_it() {
  let f = add_numbers(42, 9);
  let j = add_numbers(0, 0);
  return f + j;
}

function start_the_trace() {
  let a = add_numbers(12, 33);
  let b = calculate_it();
}

start_the_trace();

Output:

console.trace() You called add_numbers with 12 and 33 stacktrace-2.html:10:12
    add_numbers http://localhost/stacktrace/stacktrace-2.html:10
    start_the_trace http://localhost/stacktrace/stacktrace-2.html:21
    <anonymous> http://localhost/stacktrace/stacktrace-2.html:25
console.trace() You called add_numbers with 42 and 9 stacktrace-2.html:10:12
    add_numbers http://localhost/stacktrace/stacktrace-2.html:10
    calculate_it http://localhost/stacktrace/stacktrace-2.html:15
    start_the_trace http://localhost/stacktrace/stacktrace-2.html:22
    <anonymous> http://localhost/stacktrace/stacktrace-2.html:25
console.trace() You called add_numbers with 0 and 0 stacktrace-2.html:10:12
    add_numbers http://localhost/stacktrace/stacktrace-2.html:10
    calculate_it http://localhost/stacktrace/stacktrace-2.html:16
    start_the_trace http://localhost/stacktrace/stacktrace-2.html:22
    <anonymous> http://localhost/stacktrace/stacktrace-2.html:25

Get Stack Trace With a Custom Function in JavaScript

You can define a custom function that’ll produce a stack trace when an error occurs. Also, you have to place the function where an error occurs in your code.

Meanwhile, the function works so that an error in your code causes an error in the function execution. Therefore, you can see the stack trace and where it affected the function.

We have a custom function in the following code that produces a stack trace when an error occurs. So, you’ll observe the stack trace in the web browser console.

Example code:

function stack_trace() {
  function st2(f) {
    let split_string = f.toString().split('(')[0].substring(9);
    let join_string = f.arguments.join(',');
    return !f ? [] :
                st2(f.caller).concat([split_string + '(' + join_string + ')']);
  }
  return st2(arguments.callee.caller);
}

function add_num(first_number, second_number) {
  if (typeof (first_number) !== 'number' ||
      typeof (second_number) !== 'number') {
    stack_trace();
  } else {
    console.log(first_number + second_number);
  }
}

let a = 23;
let b = '23';

add_num(a, b);

Output:

Uncaught TypeError: f.arguments.join is not a function
    st2 http://localhost/stacktrace/stacktrace-3.html:12
    stack_trace http://localhost/stacktrace/stacktrace-3.html:16
    add_num http://localhost/stacktrace/stacktrace-3.html:21
    <anonymous> http://localhost/stacktrace/stacktrace-3.html:30
stacktrace-3.html:12:35

Get Stack Trace With StackTrace.js in JavaScript

StackTrace.js is a JavaScript library that you can employ to get a stack trace in your code. First, StackTrace.js requires that you define a callback function.

This callback function will print the stack trace to your web browser console. Meanwhile, behind the scenes, StackTrace.js uses the stack property from Error.stack.

In the following code, we’ve imported StackTrace.js from CDNJS. So, we defined the callback function as an arrow function, and we recreated the add_num function.

However, the add_num function uses StackTrace.js to print the stack trace.

Example code:

<head>
    <meta charset="utf-8" />
    <title>Stacktrace-4</title>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/stacktrace.js/2.0.2/stacktrace.min.js"
        integrity="sha512-9fotp9F7mNA1AztobpB07lScgCKiN4i2JuRYTl8MxiHQVJs05EJqeUfPWt9OFAKD1QsIVZiNFQSdov9luOT8TA=="
        crossorigin="anonymous"
        referrerpolicy="no-referrer">
    </script>
</head>
<body>
    <script>
        var callback = function (stack_frames) {
            var stringified_stack = stack_frames.map((the_stack_frame) => {
                return the_stack_frame.toString();
            }).join('\n');
            console.log(stringified_stack);
        };

        function addNum(n1, n2) {
            if (typeof(n1) !== "number" || typeof(n2) !== "number") {
                StackTrace.get().then(callback);
            } else {
                console.log(n1 + n2);
            }
        }

        let a = 23;
        let b = "23";
        addNum(a, b);
    </script>
</body>

Output:

_generateError (https://cdnjs.cloudflare.com/ajax/libs/stacktrace.js/2.0.2/stacktrace.js:28:)
get (https://cdnjs.cloudflare.com/ajax/libs/stacktrace.js/2.0.2/stacktrace.js:77:)
addNum (http://localhost/stacktrace/stacktrace-4.html:24:16)
http://localhost/stacktrace/stacktrace-4.html:32:9 stacktrace-4.html:19:12
Habdul Hazeez avatar Habdul Hazeez avatar

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

LinkedIn