22

在 JavaScript 中使用 TRY-CATCH 时,如何获取导致错误的行的行号?

在许多浏览器上,下面的代码可以很好地工作,我将获得指向引发异常的实际行的堆栈跟踪。

但是,有些浏览器没有“e.stack”。iPhone 的 safari 就是一个例子。

有没有办法获得适用于所有浏览器的行号?

try
{
   // lots of code here
   var i = v.WillGenerateError; // how to get this line number in catch??
   // lots of code here
} 
catch (e) 
{
     alert (e.stack)  // this will work on chrome, FF. will no not work on safari 
     alert (e.line)  // this will work on safari but not on IPhone
}

非常感谢!

更新:我发现 e.line 可以在 safari 上运行,但在 iPhone 上仍然不可用,最新的 iOS 版本

4

2 回答 2

6

尝试使用e.lineNumber. 例如:

try {
   var i = v.WillGenerateError;
} catch (e) {
   alert(e.lineNumber);
}
于 2012-06-11T22:19:30.583 回答
0
try {
   0();
} catch (e) {
   alert(e.line);
}

在 try...catch 块中使用 'e.line' 将给出 Mobile Safari 中错误的行号。

于 2014-07-15T21:08:34.203 回答