【问题标题】:exception.lineNumber returns "undefined" in google chrome and internet explorerexception.lineNumber 在谷歌浏览器和 Internet Explorer 中返回“未定义”
【发布时间】: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
  • 查看这个堆栈跟踪库github.com/eriwen/javascript-stacktrace

标签: javascript exception-handling cross-browser line-numbers


【解决方案1】:
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

【讨论】:

  • 这个我已经完成了。我的要求是在 try...catch 中得到这个。
  • 在使用window.onerror()时,我们会得到行号。但是如何在使用 try{}catch{} 时获取它?
  • 这个有效。
【解决方案2】:

我的机器上没有 IE,所以我不能代表它;但是在 Chrome 中,您可以通过查看 e.stack 属性并解析它来获得所需的内容。如果您在 catch 块中执行 console.dir(e),您可以看到可用的选项。

【讨论】:

    猜你喜欢
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2017-09-28
    • 2018-03-19
    • 2011-11-27
    相关资源
    最近更新 更多