javascript - exception.lineNumber 在谷歌浏览器和 Internet Explorer 中返回 "undefined"

标签 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);
}

我在 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/

相关文章:

php - try catch 我的整个 PHP 代码或尽可能具体是最佳实践吗?

javascript - 判断浏览器是否支持打印

javascript - spec.type 必须在 react-dnd 中定义

javascript - 使用按钮删除 DIV

javascript - 使用javascript更改导航栏的颜色

c++ - C++ 中的全局异常处理

C#(不是 ASP/MVC/WinForms)——捕获类中的所有异常

php - CSS 仅在 Firefox 中显示,其他不显示

css - Safari 中的边距百分比与 Chrome/Firefox 中的不同

c# - 我想取消页面提交,在 asp.net4.0 中使用 C# 取消确认操作