public
Last active

Custom error handling with jQuery.ajax()

  • Download Gist
ajaxOverride.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
// CUSTOM AJAX FUNCTION FOR STRUCTURED ERROR HANDLING
(function(){
// Store a reference to the original ajax method.
var originalAjaxMethod = jQuery.ajax;
var EF = function(){};
// override the default $.ajax to include special handlers for error and success
// to utilize new custom error box. existing success and error callbacks are
// left intact and given the expected params.
jQuery.ajax = function(options) {
var thisSuccess = (typeof options.success == 'function') ? options.success : EF;
var thisError = (typeof options.error == 'function') ? options.error : EF;
options.success = function(data,status,xhr) {
// do check here to see if there are errors
var theError = "";
var theMessage = "";
if (options.dataType == 'json') {
if (data.ERROR) {
theError = data.ERROR;
} else if (data.REDIRECT) {
window.location = data.REDIRECT;
return true;
} else if (data.MESSAGE) {
theMessage = data.MESSAGE;
}
// if the response is html, look for $('.display-error') and $('.display-message')
} else if (options.dataType == 'html') {
var thisResponse = $('<div>'+data+'</div>');
if (thisResponse.find('.display-error').length > 0) {
theError = thisResponse.find('.display-error').text();
} else if (thisResponse.find('.display-message').length > 0) {
theMessage = thisResponse.find('.display-message').text();
}
}
if (theError == "") {
// if not, run passed in success callback:
thisSuccess(data,status,xhr);
// if there is a message, display it now
if (theMessage != "") {
SpecifyHandleMessage(theMessage);
}
} else {
// there is an error, display it up top, don't execute the callback.
SpecifyHandleError(theError);
thisError(xhr,status,data);
}
};
options.error = function(xhr,status,error) {
SpecifyHandleError("There was an error with the request. Our team has been notified - you can rest assured that we are already looking into it!");
// also execute error callback, if one has been passed in:
thisError(xhr,status,error);
};
 
// Execute the original ajax.
return originalAjaxMethod(options);
}
})();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.