22

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?

Bryce
  • 6,440
  • 8
  • 40
  • 64
  • 2
    Does this answer your question? [Print current stack trace in JavaScript](https://stackoverflow.com/questions/43236925/print-current-stack-trace-in-javascript) – ggorlen Dec 12 '20 at 23:40
  • Thanks ggorlen, that provides another valid answer. – Bryce Dec 21 '20 at 05:37

2 Answers2

39

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

function doSomething() {
    ...
    const stackTrace = new Error().stack
    ...
} 
Tuti
  • 501
  • 1
  • 4
  • 7
15

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.

3stacks
  • 1,880
  • 1
  • 16
  • 21