简体   繁体   English

JavaScript 中的 try-catch:如何获取原始错误的堆栈跟踪或行号

[英]try-catch in JavaScript : how to get stack trace or line number of the original error

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".但是,有些浏览器没有“e.stack”。 IPhone's safari is one example. 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 上运行,但在 iPhone 上仍然不可用,最新的 iOS 版本

Try to use e.lineNumber .尝试使用e.lineNumber For example:例如:

try {
   var i = v.WillGenerateError;
} catch (e) {
   alert(e.lineNumber);
}
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 中错误的行号。

Full compatability with all browsers与所有浏览器完全兼容

var aux = err.stack.split("\n");
aux.splice(0, 2); //removing the line that we force to generate the error (var err = new Error();) from the message
aux = aux.join('\n"');
throw message + ' \n' + aux;

Error: myError at :4:11 at Object.InjectedScript._evaluateOn (:777:140).错误:myError 在 Object.InjectedScript._evaluateOn (:777:140) 处:4:11。 at Object.InjectedScript._evaluateAndWrap (:710:34).在 Object.InjectedScript._evaluateAndWrap (:710:34)。 at Object.InjectedScript.evaluate (:626:21).在 Object.InjectedScript.evaluate (:626:21)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM