抛出异常时不要停止JavaScript [英] Do not stop JavaScript when it throws an exception

查看:161
本文介绍了抛出异常时不要停止JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript编写Windows边栏小工具。现在我想把所有的JavaScript异常都捕获并记录到一个文本文件中。一个问题是当异常被抛出任何行时,下一行将不被执行。是否可以自动捕获异常,以便可以执行以下JavaScript行。



以下是演示我的问题的示例代码:

  try 
{
alert(document.getElementById(non-existing-element)。
}
catch(ex)
{
}
alert(这显示出来);
alert(document.getElementById(non-existing-element)。value);
alert(这不显示);所以一个大的try-catch方法可以允许记录错误,但其余的代码将会不执行
一个解决方案是捕捉每一行的错误。但数千行的代码太多了。 (或者我写一个宏为我做这个)
也许任何人都可以帮助我。



谢谢。

解决方案

而不是试图捕捉错误,您应该尝试构建适当的逻辑来控制它们。

  var myEle = document.getElementById(non-existing-element)

if(myEle!= null)
alert(dmyEle.value);

但是您正在描述抑制错误



您可以使用onerror事件处理程序阻止JavaScript中的错误。

  function handleErr(msg,url, line_no){
var errorMsg =Error:+ msg +\\\
;
errorMsg + =URL:+ url +\\\
;
errorMsg + =Line:+ line_no +\\\
\\\
;

alert(errorMsg);

返回true;
}

//设置全局onerror;
onerror = handleErr;

更多信息这里


I am writing a Windows Sidebar Gadget using JavaScript. Now I would like to have all JavaScript exceptions caught and logged to a text file. One problem is that when an exception is thrown at any line, the next line will not be executed. Is it possible to catch exceptions automatically so that the following line of JavaScript can be executed.

Here is the sample code which demonstrates my problem:

try
{
    alert(document.getElementById("non-existing-element").value);
}
catch(ex)
{
}
alert("This is shown.");
alert(document.getElementById("non-existing-element").value);
alert("This is not shown.");

So one big try-catch-method whould allow to log the error but the rest of the code would not be executed. One solution would be to catch errors for every line. But would be too much code for several thousand lines. (or I write a macro which does this for me) Maybe anyone can help me.

Thank you.

解决方案

Instead of trying to catch errors, you should be trying to build proper logic to control them.

var myEle = document.getElementById("non-existing-element")

if (myEle != null)
   alert(dmyEle.value);

But you are describing suppressing errors

You can suppress error in JavaScript with a onerror event handler.

function handleErr(msg, url, line_no){ 
   var errorMsg = "Error: " + msg + "\n"; 
       errorMsg += "URL: " + url + "\n"; 
       errorMsg += "Line: " + line_no + "\n\n"; 

    alert(errorMsg); 

 return true;
} 

// Set the global onerror; 
onerror = handleErr;

More information here

这篇关于抛出异常时不要停止JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆