Josh Kodroff
Josh Kodroff

Reputation: 28121

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?

Upvotes: 2

Views: 557

Answers (1)

hackattack
hackattack

Reputation: 1087

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
    }
})

Upvotes: 1

Related Questions