Wrap jQuery's $.ajax() method to define global error handling -
branching off of questions this one, i'm looking wrap jquery's $.ajax() method such can provide error handling in 1 location, used automatically of application's remote calls.
the simple approach create new name, similar how $.get() , $.post() implement facades $.ajax(). however, i'm hoping reuse name $.ajax(), such can keep rest of our code using standard jquery syntax, hiding fact we've added our own error handling. practical and/or achieve, or possibly horrible idea?
edit: responses far indicate .ajaxerror() way go. know catch 400 , 500 level errors, there way (with event handler or otherwise) catch 302 redirects well? i'm trying handle responses redirecting login page, want intercept redirect when it's xhr request, allowing user cancel action instead of forcing them forwards automatically.
you might want @ $.ajaxerror.
$(document).ajaxerror(function myerrorhandler(event, xhr, ajaxoptions, thrownerror) { alert("there ajax error!"); }); jquery provides a whole bunch of other ways attach global handlers.
to answer edit, can catch successful ajax requests $.ajaxsuccess, , can catch (successful , failed) $.ajaxcomplete. can obtain response code xhr parameter, like
$(document).ajaxcomplete(function myerrorhandler(event, xhr, ajaxoptions, thrownerror) { alert("ajax request completed response code " + xhr.status); });
Comments
Post a Comment