19

i like to catch any ajax 401 Unauthorised exception, but do no like to change all my ajax queries. Is there a way to change it for any $.ajax call like (overwrite any error handler) ?

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
MR.ABC
  • 4,712
  • 13
  • 44
  • 88
  • 3
    using google will bring you an answer in few seconds: `$.ajaxSetup({ statusCode: { 401: function(){ //this will catch any and all access denied errors } } });` – A. Wolff Aug 01 '13 at 09:23

5 Answers5

29

you can use the global ajax event handlers .ajaxError()

$( document ).ajaxError(function( event, jqxhr, settings, exception ) {
    if ( jqxhr.status== 401 ) {
        $( "div.log" ).text( "Triggered ajaxError handler." );
    }
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
13

You can do something like this:

$(function() {
    $.ajaxSetup({
        error: function(jqXHR, exception) {
            if (jqXHR.status === 401) {
                alert('HTTP Error 401 Unauthorized.');
            } else {
                alert('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
});

This will catch error in any of your ajax calls.

palaѕн
  • 72,112
  • 17
  • 116
  • 136
  • 3
    it will fail in case if an ajax call had `error` callback specified in the options like `$.ajax({url:'', error: function(){}})` – Arun P Johny Aug 01 '13 at 09:45
2

The $.ajaxSetup() function will allow you to specify global options for Ajax calls. Be careful however as other calls to ajaxSetup() will overwrite global options and specified local options to the ajax() method will override global settings.

Documentation

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

Try using .ajaxError() as a global method http://api.jquery.com/ajaxError/

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
Jordi
  • 189
  • 6
1

To catch a 401 status code simply add

  $.ajaxSetup({
    statusCode: {
      401: function(err){
        console.log('Login Failed.', err.responseJSON);
        // or whatever...
      }
    }
  });

to your page somewhere before the AJAX call is fired.

Dave Sag
  • 13,266
  • 14
  • 86
  • 134