为什么jQuery在$ .ajax成功回调中吞下异常?
看起来jQuery 1.6.4故意吞下$ .ajax成功回调中的异常.
It looks like jQuery 1.6.4 deliberately swallows exceptions in $.ajax success callbacks.
如果我这样做:
$.get('/', function() {console.log('doodoo');})
我在(Chrome)控制台中看到了这个
I get this in the (Chrome) console:
Object
doodoo
但是,如果我这样做,
$.get('/', function() {throw 'doodoo';})
我在控制台中没有看到错误:
I get no error in the console:
Object
快速浏览jQuery源代码显然表明这是故意的:
A quick look at the jQuery source code shows this is obviously intentional:
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );
}
} catch(e) { }
有人知道为什么jQuery会这样做吗?
Does anyone know why jQuery does this?
我在这里,但是原因可能是因为无论如何您都无法捕获该错误.由于它是一个回调,因此您将无法将其包装在try/catch中.如果jQuery没有捕获到它,您的应用程序将崩溃,这很可能不是您想要的.如果您需要检查错误,则将代码包装在回调内的try/catch中.
I'm guessing here, but the reason is probably because you would not be able to catch the error anyway. Since its a callback you would not be able to wrap it in a try/catch. If jQuery didn't catch it, your application would crash, which is most likely not what you want. If you need to check for errors wrap the code in a try/catch inside the callback.
try {
$.get('/', function() {throw 'doodoo';})
} catch(e) {
// this wont do anything, even if jQuery didn't catch the error
}
$.get('/', function() {
try {
throw 'doodoo';
} catch(e) {
// this is the proper way to do it
}
})