jQuery AJAX or XHR request trigger fail callbacks from done callback

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.


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.


Thanks for this question, and Chris's answer.

I tried this and it worked, except it was triggering the fail function for an implicit unexpected exception (caused by a bug), not for my test AJAX exception. Which made me thought, it might work for an explicit exception without the hassle of creating a new promise object. So I though I would try an explicit throw - and it worked.

This explicit throwing works in jQuery 3. I'm not sure about earlier versions. I tried doing this in a done handler and it didn't work: throwing only seems to work in a then handler

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

        return data; //this is also important
    }
)
.done(
    function (data, status, res) {
        //Do stuff on success
    }
)

.fail(
//Common error handler here
)
.always(
    //common always handler here
);
链接地址: http://www.djcxy.com/p/72964.html

上一篇: glibc`div()`代码中的错误?

下一篇: jQuery AJAX或XHR请求触发器未能完成回调的回调