Saj*_*ith 5 javascript exception-handling cross-browser line-numbers
我需要从 javascript 异常中获取文件名、消息、行号等。我尝试了以下代码。
try {
alertt("dddd");
} catch (e) {
console.log("ExceptionType: "+ e.name);
console.log("Message: "+ e.message);
console.log("Line No: "+ e.lineNumber);
}
Run Code Online (Sandbox Code Playgroud)
我在 Mozilla Firefox 中得到以下结果
ExceptionType: ReferenceError
消息: alertt 未定义
行号: 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)
Run Code Online (Sandbox Code Playgroud)
和 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
Run Code Online (Sandbox Code Playgroud)
两者都是字符串类型的结果。不是对象。所以它需要从这个巨大的字符串中提取行号。但问题是两者的结果并不相同。一个在第一行显示行号,另一个在第二行显示它。所以很难从这个巨大的字符串中提取行号。
是否有任何方法可以将堆栈跟踪作为对象获取?
window.onerror = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助你。检查此链接:http://www.tutorialspoint.com/cgi-bin/practice.cgi ?file=javascript_40