Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a JS stack trace without halting the script? [duplicate]

If you throw in JavaScript, the thrown error will usually propagate to the window.onerror handler which can stop the further execution of a script.

Is there any way to get a stack trace from within a function without causing this halting of execution?

like image 508
Bryce Avatar asked Jan 11 '17 08:01

Bryce


People also ask

How can I get stack trace in my browser?

You can easily see the stack trace in JavaScript by adding the following into your code: console. trace(); And you'll get an outputted stack trace.

Can JavaScript stack overflow?

Stacks JavaScript is currently included within various Stack Overflow projects automatically. If you're working on a Stack Overflow project, chances are it's already available for you!

What is Callstack in JS?

A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.

How do you stack trace?

You can obtain a stack trace from a thread – by calling the getStackTrace method on that Thread instance. This invocation returns an array of StackTraceElement, from which details about stack frames of the thread can be extracted.


2 Answers

You can also just create a new error without throwing it and use the stack trace

function doSomething() {
    ...
    const stackTrace = new Error().stack
    ...
} 
like image 142
Tuti Avatar answered Oct 12 '22 23:10

Tuti


Throwing an error will halt the stack unless caught by a try/catch.

function getStack() {
    try {
        throw new Error();
    } catch(e) {
        return e.stack;
    }
}

Invoking getStack from within any function will print out the stack from there.

Note, the method names in the stack are not affected by sourcemaps, so if you're dealing with minified code you might still get obfuscated names.

like image 39
3stacks Avatar answered Oct 13 '22 00:10

3stacks