如何处理所有AJAX调用的特定HTTP错误?

时间:2022-04-22 05:32:15

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.

我有一个web应用程序,通过AJAX请求和发送数据,作为响应,我的服务器端会根据情况发送HTTP状态代码。例如,如果用户在登录时尝试登录,我可能会返回400个HTTP状态码。最后我用警报来处理。

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.

但是处理这些HTTP状态码太麻烦了,因为我正在大量使用AJAX。这意味着我将对每个AJAX请求反复处理HTTP状态代码,这将导致重复的代码,这是一个糟糕的做法。

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.

所以,我要找的是一种处理所有这些错误的方法,所以我只处理所有的400,401,等等。

What i'm currently doing:

我现在在做什么:

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

手动处理每个AJAX调用的错误。通过使用$.ajax()中的statusCode。

  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.

对我来说,随着我的web应用程序的发展,随着我创建更多的ajax调用,这似乎有点过头了。我会一遍又一遍地重复这段代码。

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

目前,我唯一的想法是创建一个可以在AJAX之上工作的函数,比如:

    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 个解决方案

#1


11  

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

您可以使用$. ajaxsetup()来注册全局错误状态处理程序。

Description: Set default values for future Ajax requests.

说明:为将来的Ajax请求设置默认值。

Example:

例子:

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

#1


11  

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

您可以使用$. ajaxsetup()来注册全局错误状态处理程序。

Description: Set default values for future Ajax requests.

说明:为将来的Ajax请求设置默认值。

Example:

例子:

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