Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

javascript - 引发异常时如何获取JavaScript堆栈跟踪?(How can I get a JavaScript stack trace when I throw an exception?)

If I throw a JavaScript exception myself (eg, throw "AArrggg" ), how can I get the stack trace (in Firebug or otherwise)?

(如果我自己抛出JavaScript异常(例如, throw "AArrggg" ),如何获取堆栈跟踪(在Firebug或其他方式中)?)

Right now I just get the message.

(现在我才收到消息。)

edit : As many people below have posted, it is possible to get a stack trace for a JavaScript exception but I want to get a stack trace for my exceptions.

(编辑 :正如下面许多人所发布的,可以获取JavaScript异常的堆栈跟踪,但是我想获取我的异常的堆栈跟踪。)

For example:

(例如:)

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

When foo is called, I want to get a stack trace which includes the calls to foo , bar , bar .

(调用foo ,我想获得一个堆栈跟踪,其中包括对foobarbar的调用。)

  ask by David Wolever translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit 2 (2017):

(编辑2(2017):)

In all modern browsers you can simply call: console.trace();

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

(MDN Reference)

((MDN参考))

Edit 1 (2013):

(编辑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:

(正如对原始问题的评论中所指出的那样,更好(或更简单)的解决方案是使用Error对象的stack属性,如下所示:)

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.

(提供调用函数的名称以及URL,其调用函数等。)

Original (2009):

(原创(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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...