jQuery: Global AJAX Error Handler

Here’s a quick and dirty way to handle AJAX errors globally if you are using jQuery:

 
$(document).ready(function () {
	$.ajaxSetup({
		error: function (x, e) {
			if (x.status == 0) {
				alert('Network error');
			} else if (x.status == 404) {
				alert('404 Page not found'); 
			} else if (x.status == 500) {
				// assume msft brings error page back with a useful title
				var titleMatch = /(.*?)<\/title>/.exec(x.responseText); 
				var titleString = titleMatch ? titleMatch[1] : '';
				alert('Oops!\n\n500 Internal Server Error\n\n' + titleString);
			} else if (e == 'parsererror') {
				alert('Error.\nParsing JSON Request failed.');
			} else if (e == 'timeout') {
				alert('Request Time out.');
			} else {
				alert('Unkown error: ' + x.status + ' ' + x.statusText + '\n\n' + x.responseText);
			}
		}
		});
});

Now, of course you most likely wouldn’t want to just use an alert() call to notify your users, but hopefully this helps get you started. Also, using a global handler isn’t always the best option; look into using the jQuery .ajaxError() method of handling errors for specific AJAX calls as well.

This entry was posted in JavaScript, jQuery. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *