How to handle specific HTTP error for all AJAX cal

2019-03-20 13:32发布

问题:

I have a web app, requesting and sending data via AJAX, and as a response, my server-side sends HTTP status codes, depending on the situation. so for example if a user tries to login while he's logged I probably return a 400 HTTP status code. And eventually i handle it with an alert, etc.

But handling these HTTP Status codes gets too heavy, since I'm making heavy use of AJAX. that means I'll be handling HTTP status code repeatedly with every AJAX request, which will result in duplicated code, and that's a bad practice.

So, what I'm looking for is a way to handle all these errors in one place, so I just handle all 400, 401, etc with the same code.

What i'm currently doing:

Handling the errors manually for each AJAX call. By using the statusCode in$.ajax().

  statusCode: {
        500: function(data) {
            alert('Some friendly error message goes here.');
        }

It seems like an overkill for me, as my web app develops, and as I create more ajax calls. I'll be repeating this piece of code again and again.

Currently, the only idea I have in mind is creating a function that will work on top of AJAX, something like:

    function doAjax(type,url, data, moreVars) {
//this function is just a SIMPLE example, could be more complex and flexible.
        $.ajax({
            type: type,
            url: url,
            data: data,
            moreOptions:moreVars,
            //now handling all status code.
            statusCode: {
                //handle all HTTP errors from one place.
            }
        });
    }

    doAjax("POST", 'mydomain.com/login.php', dataObj);

回答1:

You can use $.ajaxSetup() to register global error state handlers.

Description: Set default values for future Ajax requests.

Example:

$.ajaxSetup({
    statusCode: {
        500: function(data) {
            alert('Some friendly error message goes here.');
        } 
    }   
});