How to handle specific HTTP error for all AJAX calls?

旧城冷巷雨未停 提交于 2019-12-04 12:10:52

问题


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.');
        } 
    }   
});


来源:https://stackoverflow.com/questions/11705684/how-to-handle-specific-http-error-for-all-ajax-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!