2

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?

  • What do you mean by "full stack trace"? I think you do have the full trace – evolutionxbox Mar 23 '23 at 17:03
  • That is the full stack trace. You've got it. `VM3498:2 Error at f (:2:17)` – TKoL Mar 23 '23 at 17:05
  • add parameter to setTimeout function example //1s = 1000ms setTimeout(f,1000); – Gultekin Ahmed Mar 23 '23 at 17:11
  • 1
    I updated the question above, the stack I get from the Error object is not complete as it lacks the entries relative to the setTimeout and f1 functions – Gianluca De Stefano Mar 23 '23 at 17:23
  • 2
    Javascript is a scripting language, in the original meaning of that term. There are things that are tracked by host environment for it's own use (for example [internal \[slot\] properties](https://stackoverflow.com/questions/33075262/what-is-an-internal-slot-of-an-object-in-javascript)) that are not necessarily available programmatically in Javascript. I hope somebody proves me wrong, but I suspect that this is one of those times where that information is not available to you. – Jared Smith Mar 23 '23 at 17:26

1 Answers1

2

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.

Feathercrown
  • 2,547
  • 1
  • 16
  • 30