Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX or XHR request trigger fail callbacks from done callback

Tags:

jquery

Is there a way in my done handler of a jQuery XHR (created from a $.get() call) to look for problems in the response and then trigger the registered subsequent handlers (lie fail & always) with a custom error message?

something like this:

$.get( URL )
.done(
    function (data, status, res) {
    if(/*some condition*/){
            this.Reject(res, status, "some reason");
            return    
        }
    //Do stuff on success
    }
)

.fail(
//Common error handler here
)
.always(
    //common always handler here
);

Kind of a secondary filter on done. The reason is of course all the APIs that shove an error in a 200 response that jQuery could never know was an error.

like image 994
Chris DaMour Avatar asked Jul 23 '13 00:07

Chris DaMour


1 Answers

I figured out how to do this, and it works nicely:

$.get( URL )
.then(
    function (data, status, res) {
        if(/**some error check**/({
             return $.Deferred().reject(res, status, "error message");
        }

        return $.Deferred().resolve(data, status, res);
    }
)
.done(
    function (data, status, res) {
        //Do stuff on success
    }
)

.fail(
//Common error handler here
)
.always(
    //common always handler here
);

works like a charm, now i don't have messy data error handling in my done, i can just focus on processing data or setting error messages.

like image 75
Chris DaMour Avatar answered Sep 25 '22 07:09

Chris DaMour