jQueryexception处理

有什么办法可以在javascript中捕获任何未捕获的exception吗? 我的意思是,我所有的“危险”代码都在try-catch块中。 但是我没有明确处理的exception呢? 我正在使用jQuery,我的主要javascript文件以:

$(document).ready(function(){})

在这里我将一些事件绑定到一些DOM元素。 我可以在这里使用try-catch块,但它们将捕获在事件绑定过程中发生的exception,而不是在事件处理期间。 但是,如果我在每个事件处理函数中使用try-catch块,那将是丑陋的。

我应该如何捕获未在我的显式try-catch块中出现的exception? (我不想写一般处理函数,我只是想把问题发送到我的服务器)

你可以编写一个函数来将你的真实处理程序包装在try / catch中

 function tc(func, msg) { msg = msg || "Handler exception"; return function(e) { try { return func(e); } catch (exc) { $.post( /* send exception to server? */ ); throw exc; // let nature take its course } }; } 

(可能希望通过参数处理等获得更好的function)然后当你绑定处理程序时,你会做:

 $('#whatever').click(tc(function(e) { // your handler function }, "This is the message sent to the server when this handler fails")); 

您可以使用window.onerror事件处理程序,虽然它在Opera中不受支持,但在某些情况下它可能不会触发 (感谢@Josh)。

这样做并不是明智之举,但是,它会让bug找到一个噩梦。 通常最好先确保你的代码没有错误:-)你当然不需要在JavaScript中经常使用try... catch语句,你肯定不应该使用空的catch块。

我可以在这里使用try-catch块,但是它们会捕获在事件绑定过程中发生的exception,而不是在事件处理期间。

您还可以向内部范围添加try / catch块:

 // Outer try { $(document).ready(function(){}) } catch (e) { /* Error handling */ } // Inner $(document).ready(function(){ try { /* ... */ } catch (e) { /* Error handling */ } }); 

怎么样

  function func_madness() { throw("This function is throwing exceptions, because \n" + "it can not throw polar bears and whales.\n"); } // func_madness window.onload = function () { try { func_madness(); } catch (err) { document.write("Caught it!\n
\n" + err); } // catch } // window.onload