如果我自己抛出一个JavaScript异常(例如,抛出“AArrggg”),我如何获得堆栈跟踪(在Firebug或其他)?现在我刚收到消息。

编辑:正如下面许多人发布的那样,可以为JavaScript异常获得堆栈跟踪,但我想为我的异常获得堆栈跟踪。例如:

function foo() {
    bar(2);
}
function bar(n) {
    if (n < 2)
        throw "Oh no! 'n' is too small!"
    bar(n-1);
}

当调用foo时,我想获得一个堆栈跟踪,其中包括对foo, bar, bar的调用。


当前回答

使用Chrome浏览器,可以使用控制台。跟踪方法:https://developer.chrome.com/devtools/docs/console-api#consoletraceobject

其他回答

在Firefox上比在IE上更容易获得堆栈跟踪,但从根本上来说,这是你想要做的:

将“有问题的”代码段包装在try/catch块中:

try {
    // some code that doesn't work
    var t = null;
    var n = t.not_a_value;
}
    catch(e) {
}

如果你要检查"error"对象的内容,它包含以下字段:

e.fileName:问题产生的源文件/页 e.lineNumber:出现问题的文件/页中的行号 message:描述发生错误类型的简单消息 e.name:发生错误的类型,在上面的例子中它应该是'TypeError' e.stack:包含导致异常的堆栈跟踪

我希望这能帮到你。

在谷歌Chrome(版本19.0及以上)中,简单地抛出异常就可以完美地工作。例如:

/* file: code.js, line numbers shown */

188: function fa() {
189:    console.log('executing fa...');
190:    fb();
191: }
192:
193: function fb() {
194:    console.log('executing fb...');
195:    fc()
196: }
197:
198: function fc() {
199:    console.log('executing fc...');
200:    throw 'error in fc...'
201: }
202:
203: fa();

将显示浏览器控制台输出的堆栈跟踪:

executing fa...                         code.js:189
executing fb...                         code.js:194
executing fc...                         cdoe.js:199
/* this is your stack trace */
Uncaught error in fc...                 code.js:200
    fc                                  code.js:200
    fb                                  code.js:195
    fa                                  code.js:190
    (anonymous function)                code.js:203

希望这对你有所帮助。

编辑2 (2017):

在所有现代浏览器中,您可以简单地调用:console.trace();(MDN引用)

编辑1 (2013):

一个更好(也更简单)的解决方案是使用Error对象的stack属性,就像在原始问题的评论中指出的那样:

function stackTrace() {
    var err = new Error();
    return err.stack;
}

这将产生如下输出:

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

给出调用函数的名称以及URL、它的调用函数等等。

原(2009):

这段代码的修改版本可能会有所帮助:

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);
}

我必须在IE11中研究smartgwt中的无尽递归,因此为了更深入地研究,我需要一个堆栈跟踪。但问题是,我无法使用开发控制台,因为这样的复制更加困难。 在javascript中使用以下方法:

try{ null.toString(); } catch(e) { alert(e.stack); }

在Firefox中,似乎不需要抛出异常。这就足够了

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