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


当前回答

至少在Edge 2021中:

console.groupCollapsed('jjjjjjjjjjjjjjjjj')
    console.trace()
    try {
        throw "kuku"
    } catch(e) {
        console.log(e.stack)
    }
console.groupEnd()
traceUntillMe()

你完了,我的朋友

其他回答

我不认为有什么内置的东西可以使用,但我确实发现了很多人自己卷的例子。

DIY javascript堆栈跟踪 任何浏览器中的Javascript堆栈跟踪

哇——我在6年里没有看到一个人建议我们在使用堆栈之前先检查它是否可用!在错误处理程序中,最糟糕的事情就是因为调用了不存在的东西而抛出错误。

正如其他人所说,虽然stack现在使用起来很安全,但在IE9或更早的版本中不受支持。

我记录我的意外错误和堆栈跟踪是相当必要的。为了获得最大的支持,我首先检查Error.prototype.stack是否存在并且是一个函数。如果是,那么使用error.stack是安全的。

        window.onerror = function (message: string, filename?: string, line?: number, 
                                   col?: number, error?: Error)
        {
            // always wrap error handling in a try catch
            try 
            {
                // get the stack trace, and if not supported make our own the best we can
                var msg = (typeof Error.prototype.stack == 'function') ? error.stack : 
                          "NO-STACK " + filename + ' ' + line + ':' + col + ' + message;

                // log errors here or whatever you're planning on doing
                alert(msg);
            }
            catch (err)
            {

            }
        };

编辑:似乎因为堆栈是一个属性而不是一个方法,你可以安全地调用它,即使在旧的浏览器。我仍然感到困惑,因为我非常确定检查错误。原型以前为我工作,现在它不-所以我不确定发生了什么。

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

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

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

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

详见V8文档