leora
leora

Reputation: 196891

What is the best way to globally catch ajax errors in asp.net-mvc?

I find myself putting this (simplified) code in a number of different javascript files:

 $(document).ajaxError(function (e, xhr, settings, exception) {
     alert('error in: ' + 
                         settings.url + ' \\n' + 
                         'error:\\n' + exception + 
                         ": " + xhr.responseText
          );
 });

is there any downside that someone can think of by just putting this in my Site.Master file once so I have a consistent solution to errors?. If I do that, is there anyway to override the behavior on a specific page?

Upvotes: 0

Views: 236

Answers (1)

Karl Anderson
Karl Anderson

Reputation: 34834

Use $(document).ajaxError in your Site.Master file.

To override this in a specific instance, then just include the error callback on individual AJAX calls, like this:

$.ajax({
    url: '/yourUrl',
    success: function(result) {
        alert('It worked!');
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert('Your custom error message here.');
    }
});

For those that you do not want to override, them omit the error callback.

Upvotes: 1

Related Questions