18

How to I get a backtrace in Javascript?

Ideal features:

  • entry function name, or some meaningful identifier for anonymous functions,
  • argument list at each level,
  • line numbers.

Can this be done in standard ECMAScript?

If not, can it be done in the common web browser dialects?

Thanks.

Edit --

Thanks for your suggestions.

My dialect doesnot support arguments.caller or arguments.callee.

I can do this:

try {
    let x = null;
    x .foo ();
}
catch (e) {
        debug (dump (e.stack));
}

Which gets me the information as a string, which is okay for at-a-glance, but it would be a great help to walk e.stack. Does it have a standard form?

Thanks again.

Community
  • 1
  • 1
spraff
  • 32,570
  • 22
  • 121
  • 229

3 Answers3

39

In my debugging experience, I always use this

(function () { console.log(new Error().stack); })();

As the comments below suggested, the readers should prefer: console.log(new Error().stack);

linzuojian
  • 602
  • 6
  • 8
  • 5
    Why the extra function wrapper? can't you just use `console.log(new Error().stack);`? It worked for me. – Daniel Tonon Aug 30 '17 at 02:15
  • 1
    I don't see any reason for the wrapper function either – Timo Huovinen Jun 15 '18 at 13:19
  • 1
    I like clean global scope. So I add a wrapper. – linzuojian Feb 28 '19 at 09:00
  • Adding the wrapper function obviously adds an extra function (pointlessly?) to top of the stack, making the code you care about one step down. I recommend readers don't do this, idk if the poster had a reason for wanting it this way so I won't change the answer. – DanielM Apr 25 '19 at 09:52
9

Another way is to use console.trace();

source: https://developer.mozilla.org/en-US/docs/Web/API/Console/trace

Lafif Astahdziq
  • 3,788
  • 29
  • 38
3

This lib: stacktrace-js works anywhere, not only with errors.

Example:

StackTrace.get()
    .then(stack => { console.log(stack) })
    .catch(err => { console.log(err) });
paul.ago
  • 3,904
  • 1
  • 22
  • 15