JQuery AJAX or XHR request request calls callbacks from executed callback

Is there a way in my jQuery XHR handler (created from a call to $ .get ()) to look for problems in the response and then run the registered subsequent handlers (false fails and always) with a custom error message?

something like that:

$.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 ); 

Type of secondary filter. The reason, of course, is that all the APIs that cause an error in the 200 response that jQuery will never recognize were an error.

+7
jquery
source share
2 answers

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

 $.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 the dirty data error handling in my done, I can just focus on processing the data or setting up error messages.

+4
source share

Thanks for this question, and Chris answered.

I tried this and it worked, except that it ran the crash function for an implicit unexpected exception (caused by an error), and not for my AJAX test exception. This made me think that this might work for a clear exception without the hassle of creating a new promise object. Therefore, although I would try an explicit throw - and it worked.

This explicit metalism works in jQuery 3. I'm not sure about earlier versions. I tried to do this in the done handler, and it did not work: throwing only seems to work in the 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 ); 
0
source share

All Articles