jQuery deferred: throw and catch an exception in the fail() callback

javascript, jquery, promise

Solution

No, you can't do that. That's not how exception handling works with promises.

The code inside the `done` clause is not executed in the same time or context as the try/catch. You can't asynchronously catch exceptions like that (yet!) in the browser.

My suggestion is treat the `.fail` clause as the catch.

jQuery.ajax('http://www.someurlthatwillproduceanerror.com')
    .fail(function () {
        console.log("an exception"); // the handler here!
    })
    .done(function () {
        console.log('ok');
    });

Note that the code that does something based on the exception does not have to be in the same place as the code declaring the promise.

var p = jQuery.ajax('http://www.someurlthatwillproduceanerror.com');
... 
...
p.fail(function(){ /* I'm handling it here */}); // .catch in modern promise libs

In general, it might be a good idea to return the promise from functions that deal with promises - that usually produces cleaner code.

Problem

I am trying to make an ajax request and throw an exception when it fails. Unfortunately I am not able to catch the exception. My code looks like this: ``` try { jQuery.ajax('http://www.someurlthatwillproduceanerror.com') .fail(function () { throw 'an exception'; }) .done(function () { console.log('ok'); }) ; } catch (e) { console.log(e); } ``` I would expect the code to catch the exception and log 'an exception' to the console. Instead I end up with an uncaught exception. Does anyone know how to handle exceptions in this case?

Original source

Related problems