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?