JavaScript 中的 try-catch:如何获取原始错误的堆栈跟踪或行号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10988169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
try-catch in JavaScript : how to get stack trace or line number of the original error
提问by Greg Balajewicz
When using TRY-CATCH in JavaScript, how to get the line number of the line that caused the error?
在 JavaScript 中使用 TRY-CATCH 时,如何获取导致错误的行的行号?
On many browsers, the below code will work great and I will get the stack trace that points to the actual line that throw the exception.
在许多浏览器上,下面的代码会很好用,我将获得指向引发异常的实际行的堆栈跟踪。
However, some browsers do not have "e.stack". IPhone's safari is one example.
但是,有些浏览器没有“e.stack”。iPhone 的 safari 就是一个例子。
Is there someway to get the line number that will work for all browsers?
有没有办法获得适用于所有浏览器的行号?
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
}
Many thanks!
非常感谢!
UPDATE: I found that e.line works on safari but still not available on IPhone, latest iOS version
更新:我发现 e.line 可以在 safari 上运行,但在最新的 iOS 版本 iPhone 上仍然不可用
回答by Victor
Try to use e.lineNumber
.
For example:
尝试使用e.lineNumber
. 例如:
try {
var i = v.WillGenerateError;
} catch (e) {
alert(e.lineNumber);
}
回答by Seanonymous
try {
0();
} catch (e) {
alert(e.line);
}
Using 'e.line' in a try…catch block will give the line number of the error in Mobile Safari.
在 try...catch 块中使用 'e.line' 将给出 Mobile Safari 中错误的行号。