Search code examples
asp.net-mvc.net-5jquery-ajaxq

Jquery ajaxsetup: Catch only 401 error else let the custom error handler do the job


I have a complex application (.NET 5 MVC 5) which does various ajax calls. I would like to globally handle only 401 unauthorized requests.

This classic code does the trick as it catches globally

$.ajaxSetup({
    error: function (jqXHR, textStatus, errorThrown) {
        if (jqXHR.status == 401) {//Unauthorized
            //it will redirect to the same document, so authentication will take place and will go back to login
            window.location.href = document.URL;
        }
    }
});

But it catches globally everything while I need it to catch only 401 and let the defined error function do the rest.

What I mean is, for example I have:

function dropYear_changed(data) {
    $.ajax({
     url: '@Url.Action("aaa", "vvv")',
     type: "get",
     contentType: 'application/x-www-form-urlencoded',
     data: data,
        success: function (result) {
            //Do stuff
     },
     error: function(error) {
     //show some alert, toast, do error stuff
     }
 });
}

with the global ajax it won't do the

//show some alert, toast, do error stuff

because the ajaxSetup will take over. I want to catch 401 globally but do something else if error is not 401, and that something else is defined in the ajax error:

How I can do this?


Solution

  • You can catch only specific errors in $.ajaxSetup with statusCode function. Try below code:

    $.ajaxSetup({
        statusCode: {
            401: function() {
                alert("401");
            }
        }
    });
    

    This function alert when the response status is a 401. This way you can catch 401 globally and do something else if error is not 401.