Javascript backtrace
Asked Answered
S

3

19

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.

Stribling answered 22/7, 2011 at 8:54 Comment(3)
The best way to get strack traces is to use browser based debuggers.Clepsydra
What is your dialect ? What is dump ?Clepsydra
It's a proprietry dialect, seems mostly complete, has a few extentions.Stribling
M
42

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);
Merit answered 10/6, 2015 at 3:22 Comment(4)
Why the extra function wrapper? can't you just use console.log(new Error().stack);? It worked for me.Bream
I don't see any reason for the wrapper function eitherEgghead
I like clean global scope. So I add a wrapper.Merit
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.Ragman
D
10

Another way is to use console.trace();

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

Diesis answered 7/3, 2020 at 14:23 Comment(0)
M
3

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

Example:

StackTrace.get()
    .then(stack => { console.log(stack) })
    .catch(err => { console.log(err) });
Magnify answered 10/1, 2018 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.