Javascript exception stack trace
Asked Answered
D

4

103

In Firefox I can get the stack trace of an exception by using exception.stack.

Is there a way to get that in other browsers, too?

Edit: I actually want to save the stack trace automatically (if possible) and not debug it at the time (i.e. I know how to get the stack trace in a debugger).

Deadfall answered 29/9, 2008 at 8:11 Comment(0)
A
90

Place this line where you want to print the stack trace:

console.log(new Error().stack);

Note: tested by me on Chrome 24 and Firefox 18

May be worth taking a look at this tool as well.

Adah answered 28/1, 2013 at 13:2 Comment(3)
Sweet - I use a combination of onerror to get the line number and then wrap the offending line with a try catch and your suggestion to alert the stacktrace back to the user. ` window.onerror = function(message, url, lineNumber) { alert('message: ' + message + ' - url: ' + url + ' - ln: ' + lineNumber); return true; }; ` Then wrap it to print out the stacktrace. ` try { // Some code that is causing the exception. } catch(e) { alert(new Error().stack); } `Aenea
somehow dies only gives me the first line of the stack. What am I doing wrong?? i.e.: function foo() { fdasmkl } try { foo() } catch(e) { err = new Error(e).stack; console.log(err) } =>>> Error: ReferenceError: fdasmkl is not defined at <anonymous>:6:7 instead of "Error: ReferenceError: fdasmkl is not defined at eval (eval at <anonymous> (:6:1), <anonymous>:1:1) at <anonymous>:6:1"Braces
nevermind, found the issue. Since it was an error already, I can do: function foo() { fdasmkl } try { foo() } catch(e) { console.log(e.stack) } immediatelyBraces
M
24

Webkit now has functionality that provides stack traces:

Web Inspector: Understanding Stack Traces, posted by Yury Semikhatsky on Wednesday, April 20th, 2011 at 7:32 am (webkit.org)

From that post:

Merits answered 21/4, 2011 at 10:48 Comment(2)
Much more convenient than creating an exception just to view its stack.Agitator
The link is broken, but I think there is a copy here pjh0718.blogspot.com/2016/02/…Beseem
M
3

If you want the string stack trace, I'd go with insin's answer: stacktrace.js. If you want to access the pieces of a stacktrace (line numbers, file names, etc) stackinfo, which actually uses stacktrace.js under the hood.

Milanmilanese answered 22/4, 2014 at 22:30 Comment(0)
H
0

Not really, at least not easily.

In IE, you can debug the browser process with MS Script Debugger (which for some reason is an Office component) or Visual Studio, and then you can see the stack on breakpoints.

Herren answered 29/9, 2008 at 8:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.