【发布时间】:2013-11-05 04:46:57
【问题描述】:
我需要从 javascript 异常中获取文件名、消息、行号等。我尝试了以下代码。
try {
alertt("dddd");
} catch (e) {
console.log("ExceptionType: "+ e.name);
console.log("Message: "+ e.message);
console.log("Line No: "+ e.lineNumber);
}
我在 Mozilla Firefox 中得到以下结果
ExceptionType: ReferenceError
消息:警报未定义
行号: 4
但相同的代码在 Google Chrome、Internet Explorer 中给出了以下结果
ExceptionType: ReferenceError
消息:警报未定义
行号:未定义
它没有给出行号。如何解决这个问题?有没有其他获取行号的方法?
我试过 e.stack 它将堆栈跟踪作为字符串返回。 它在 Google Chrome 中给了我以下输出
ReferenceError: alertt is not defined
at message (http://localhost/ems-test/js/test.js:4:4)
at HTMLDocument.<anonymous> (http://localhost/ems-test/js/test.js:14:2)
at c (http://localhost/ems-test/js/jquery-1.10.2.min.js:4:26036)
at Object.p.fireWith [as resolveWith] (http://localhost/ems-test/js/jquery-1.10.2.min.js:4:26840)
at Function.x.extend.ready (http://localhost/ems-test/js/jquery-1.10.2.min.js:4:3305)
at HTMLDocument.q (http://localhost/ems-test/js/jquery-1.10.2.min.js:4:717)
firefox 给出了这个结果
message@http://localhost/ems-test/js/test.js:4
@http://localhost/ems-test/js/test.js:14
x.Callbacks/c@http://localhost/ems-test/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost/ems-test/js/jquery-1.10.2.min.js:4
.ready@http://localhost/ems-test/js/jquery-1.10.2.min.js:4
q@http://localhost/ems-test/js/jquery-1.10.2.min.js:4
两者都是字符串类型的结果。不是一个对象。所以它需要从这个巨大的字符串中提取行号。但问题是两者的结果都不一样。一个在第一行显示行号,另一个在第二行显示。所以很难从这个巨大的字符串中提取行号。
有什么方法可以将堆栈跟踪作为对象获取吗?
【问题讨论】:
-
错误对象 API 未标准化。
-
还有其他获取行号的方法吗?
-
我不知道在 Internet Explorer 或 Chrome/Safari 中有什么方法可以做到这一点,但也许有人会这样做。
-
可能堆栈包含行号:e.stack
标签: javascript exception-handling cross-browser line-numbers