如果我自己抛出一个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的调用。


当前回答

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

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

其他回答

使用console.error(e.stack) Firefox只在日志中显示堆栈跟踪, Chrome也会显示这条消息。 如果邮件中包含重要信息,这可能是一个糟糕的惊喜。两者都要记录日志。

Chrome/Chromium和其他使用V8的浏览器,以及Firefox,都有一个方便的接口来通过Error对象的stack属性获取堆栈跟踪:

    try {
        // Code throwing an exception
        throw new Error();
    } catch(e) {
        console.log(e.stack);
    }

详见V8文档

这里有一个答案,给你最大的性能(IE 6+)和最大的兼容性。兼容IE 6!

function stacktrace( log_result ) { var trace_result; // IE 6 through 9 compatibility // this is NOT an all-around solution because // the callee property of arguments is depredicated /*@cc_on // theese fancy conditinals make this code only run in IE trace_result = (function st2(fTmp) { // credit to Eugene for this part of the code return !fTmp ? [] : st2(fTmp.caller).concat([fTmp.toString().split('(')[0].substring(9) + '(' + fTmp.arguments.join(',') + ')']); })(arguments.callee.caller); if (log_result) // the ancient way to log to the console Debug.write( trace_result ); return trace_result; @*/ console = console || Console; // just in case if (!(console && console.trace) || !log_result){ // for better performance in IE 10 var STerror=new Error(); var unformated=(STerror.stack || STerror.stacktrace); trace_result = "\u25BC console.trace" + unformated.substring(unformated.indexOf('\n',unformated.indexOf('\n'))); } else { // IE 11+ and everyone else compatibility trace_result = console.trace(); } if (log_result) console.log( trace_result ); return trace_result; } // test code (function testfunc(){ document.write( "<pre>" + stacktrace( false ) + "</pre>" ); })();

如果你有firebug,在脚本选项卡中有一个“所有错误”选项。一旦脚本到达断点,你可以查看firebug的堆栈窗口:

function stacktrace(){
  return (new Error()).stack.split('\n').reverse().slice(0,-2).reverse().join('\n');
}