问题描述
如果我自己抛出JavaScript异常(例如, throwAArrggg
),我如何获得堆栈跟踪(在Firebug中或其他方式)?现在我收到消息。
If I throw a JavaScript exception myself (eg, throw "AArrggg"
), how can I get the stack trace (in Firebug or otherwise)? Right now I just get the message.
编辑:下面有很多人发布了,有可能获得一个 JavaScript异常但我希望获得 my 异常的堆栈跟踪。例如:
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. For example:
function foo() {
bar(2);
}
function bar(n) {
if (n < 2)
throw "Oh no! 'n' is too small!"
bar(n-1);
}
当 foo
是调用,我想得到一个堆栈跟踪,其中包括对 foo
, bar
,的调用bar
。
When foo
is called, I want to get a stack trace which includes the calls to foo
, bar
, bar
.
推荐答案
编辑2(2017):
在所有现代浏览器中,您只需调用: console.trace();
In all modern browsers you can simply call: console.trace();
(MDN Reference)
编辑1(2013):
原始问题的评论中指出的更好(和更简单)的解决方案是使用 stack
属性错误
对象如下:
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;
}
这将产生如下输出:
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,调用函数等。
Giving the name of the calling function along with the URL, its calling function, and so on.
原始(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);
}
这篇关于抛出异常时如何获得JavaScript堆栈跟踪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!