Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting complete stack trace as variable

I am trying to acquire the stack trace at a given position in my code as a variable.

For the moment I have been trying to use console.trace() and new Error().stack but they are not optimal. The first prints the stack to the console while I want to save it in a variable, while the latter does not correctly handle async function calls such as setTimeout.

For example, using the following code:

var getStackTrace = function() {
  var obj = {};
  Error.captureStackTrace(obj, getStackTrace);
  return obj.stack;
};

function f(){
    console.log(getStackTrace());
}

function f1(){
    setTimeout(f);
}

f1();

I only get:

VM3498:2 Error
    at f (<anonymous>:2:17)

While if I use console.trace():

function f(){
    console.trace();
}

function f1(){
    setTimeout(f);
}

f1();

I get:

f   @   VM4219:2
setTimeout (async)      
f1  @   VM4219:6
(anonymous) @   VM4219:9

That is complete but is printed directly in the console.

Is there a way to get the full stack trace or the get the output of console.trace() in a variable?

like image 965
Gianluca De Stefano Avatar asked Oct 20 '25 01:10

Gianluca De Stefano


1 Answers

I'm not completely sure here, but asynchronous calls may not actually be a part of the call stack. The console.trace() documentation says the following:

Note: In some browsers, console.trace() may also output the sequence of 
calls and asynchronous events leading to the current console.trace() which 
are not on the call stack — to help identify the origin of the current 
event evaluation loop.

If this is the case, there may be no way to get the call stack programmatically unless you rewrite all of your functions, as well as setTimeout and setInterval (and setImmediate), to manually track their calls in some way.

like image 51
Feathercrown Avatar answered Oct 21 '25 16:10

Feathercrown