How can I get a JavaScript stack trace when I throw an exception?
Edit 2 (2017):
In all modern browsers you can simply call: console.trace();
(MDN Reference)
Edit 1 (2013):
A better (and simpler) solution as pointed out in the comments on the original question is to use the stack
property of an Error
object like so:
function stackTrace() {
var err = new Error();
return err.stack;
}
This will generate output like this:
DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
Giving the name of the calling function along with the URL, its calling function, and so on.
Original (2009):
A modified version of this snippet may somewhat help:
function stacktrace() {
function st2(f) {
return !f ? [] :
st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']);
}
return st2(arguments.callee.caller);
}
Chrome/Chromium and other browsers using V8, as well as Firefox, have a convenient interface to get a stacktrace through the stack
property of Error
objects:
try {
// Code throwing an exception
throw new Error();
} catch(e) {
console.log(e.stack);
}
See details in the V8 documentation
In Firefox it seems that you don't need to throw the exception. It's sufficient to do
e = new Error();
console.log(e.stack);