我需要从 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
Message: alertt is not defined
Line No: 4
但同样的代码在 Google Chrome、Internet Explorer 中给出了以下结果
ExceptionType: ReferenceError
Message: alertt is not defined
Line No: undefined
它没有给出行号。如何解决这个问题?还有其他获取行号的方法吗?
我试过 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
都是字符串类型的结果。不是一个对象。所以它需要从这个巨大的字符串中提取行号。但问题是两者的结果都不一样。一个在第一行显示行号,另一个在第二行显示。因此很难从这个巨大的字符串中提取行号。
有什么方法可以将堆栈跟踪作为对象获取吗?
最佳答案
window.onerror = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
希望对您有所帮助。 检查此链接:http://www.tutorialspoint.com/cgi-bin/practice.cgi?file=javascript_40
关于javascript - exception.lineNumber 在谷歌浏览器和 Internet Explorer 中返回 "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19782078/