当前位置: 动力学知识库 > 问答 > 编程问答 >

Why does jQuery swallow exceptions in $.ajax success callbacks?

问题描述:

It looks like jQuery 1.6.4 deliberately swallows exceptions in $.ajax success callbacks.

If I do this:

$.get('/', function() {console.log('doodoo');})

I get this in the (Chrome) console:

Object

doodoo

But if I do this,

$.get('/', function() {throw 'doodoo';})

I get no error in the console:

Object

A quick look at the jQuery source code shows this is obviously intentional:

try {

while( callbacks[ 0 ] ) {

callbacks.shift().apply( context, args );

}

} catch(e) { }

Does anyone know why jQuery does this?

网友答案:

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
    }
})
分享给朋友:
您可能感兴趣的文章:
随机阅读: