jQuery异常处理 [英] jQuery exception handling
问题描述
$(document).ready(function(){})
这里我将某些事件绑定到某些DOM元素。我可以在这里使用try-catch块,但是它们会捕获在事件绑定过程中发生的异常,而不是事件处理期间发生的异常。但是如果我在每个事件处理函数中使用try-catch块,那将是丑陋的。
我应该如何捕获在我的显式try-catch块中没有发生的异常? (我不想写一个一般的处理函数,我只想把问题发送到我的服务器)
你可以编写一个函数,将真正的处理程序包装在一个try / catch中。
function tc(func,msg){
msg = msg || 处理者例外;
return function(e){
try {
return func(e);
}
catch(exc){
$ .post(/ *发送异常到服务器?* /);
抛出//让自然采取行动
}
};
}
(可能想让参与者处理等等)然后绑定你会做的处理程序:
$('#whatever')点击(tc(function(e){
//你的处理函数
},这是这个处理程序失败时发送到服务器的消息));
Is there any way I could catch any uncaught exception in javascript? I mean, all my "dangerous" code are in try-catch blocks. But what about exceptions that I don't handle explicitly? I'm using jQuery, my main javascript file starts with :
$(document).ready(function(){})
here I bind some events to some DOM elements. I can use try-catch blocks here, but they will catch exceptions that occur during the event binding procedure, not during the event handling. But if I used try-catch blocks in every event handling functions it would be ugly.
How should I catch exceptions that don't occur in my explicit try-catch blocks? (I don't want to write a general handler function, I just want to send the problem to my server)
You could write a function that would wrap your real handlers in a 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
}
};
}
(Might want to get fancier with argument handling etc.) Then when you bind handlers you'd do:
$('#whatever').click(tc(function(e) {
// your handler function
}, "This is the message sent to the server when this handler fails"));
这篇关于jQuery异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!