Skip to content

Instantly share code, notes, and snippets.

@dustMason
Created September 13, 2010 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustMason/577722 to your computer and use it in GitHub Desktop.
Save dustMason/577722 to your computer and use it in GitHub Desktop.
Custom error handling with jQuery.ajax()
// 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);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment