如何处理AJAX调用中的错误?

时间:2022-12-04 00:19:01

Let's say I have the following jQuery AJAX call:

假设我有以下jQuery AJAX调用:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
        // Do stuff
   }
 });

Now, when this AJAX call is made I want the server-side code to run through a few error handling checks (e.g. is the user still logged in, do they have permission to use this call, is the data valid, etc). If an error is detected, how do I bubble that error message back up to the client side?

现在,当执行此AJAX调用时,我希望服务器端代码运行一些错误处理检查(例如,用户是否仍然登录,他们是否有使用此调用的权限,数据是否有效等等)。如果检测到错误,我如何将错误消息反馈到客户端?

My initial thought would be to return a JSON object with two fields: error and errorMessage. These fields would then be checked in the jQuery AJAX call:

我最初的想法是返回一个带有两个字段的JSON对象:error和errorMessage。然后在jQuery AJAX调用中检查这些字段:

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
       if (result.error == "true") 
       {
           alert("An error occurred: " & result.errorMessage);
       }
       else 
       {
           // Do stuff
       }
   }
 });

This feels a bit clunky to me, but it works. Is there a better alternative?

这对我来说有点笨拙,但它确实有效。还有更好的选择吗?

5 个解决方案

#1


24  

Personally, I have similar code to the following code in my library.

就我个人而言,我的库中有类似的代码。

$.ajaxSetup({
    error: function(xhr){
        alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
    }
});

jQuery docs Ajax/jQuery.ajaxSetup

jQuery Ajax / jQuery.ajaxSetup文档

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function. This also means that you do not have to define an error: call in every $.ajax call.

将这个错误从服务器端(使用php)传递到客户端的最佳方式是通过Ajax请求在400的某个地方发送一个头部(这总是与错误相关)。一旦Ajax请求收到该请求,它将触发错误函数。这也意味着您不必定义一个错误:调用每一个$。ajax调用。

header('HTTP/1.0 419 Custom Error');

Quote from w3.org header information

引用w3.org头信息

Error 4xx, 5xx The 4xx codes are intended for cases in which the client seems to have erred, and the 5xx codes for the cases in which the server is aware that the server has erred. It is impossible to distinguish these cases in general, so the difference is only informational. The body section may contain a document describing the error in human readable form. The document is in MIME format, and may only be in text/plain, text/html or one for the formats specified as acceptable in the request.

错误4xx, 5xx 4xx代码用于客户端似乎有错误的情况,而5xx代码用于服务器知道服务器有错误的情况。一般情况下是无法区分这些情况的,所以这种差异只是信息上的。正文部分可以包含描述人类可读形式的错误的文档。该文档是MIME格式,并且只能是文本/纯文本、文本/html格式,或者是请求中指定的可接受格式。

#2


5  

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
        // Do stuff
   },
   error: function(request,status,errorThrown) {
        // There's been an error, do something with it!
        // Only use status and errorThrown.
        // Chances are request will not have anything in it.
   }
 });

#3


3  

Doesn't the jQuery ajax function accept one more parameter at the end, a callback for failed calls? If so, just add a fail:function(...){..} after the success callback.

jQuery ajax函数难道不接受最后的另一个参数——失败调用的回调吗?如果是这样,只需添加一个fail:function(…){.. .成功回调之后。

#4


0  

Return an error code on the server side using the HTTP error the best equates to what the error is. Then use the error callback. This will also allow you to show errors given by your webserver.

在服务器端使用HTTP错误返回错误代码,最好与错误的值相等。然后使用错误回调。这也允许您显示webserver给出的错误。

#5


0  

It's pretty late to answer this question but I think It will be beneficial to some one using es6 and jquery 2.2.

现在回答这个问题已经很晚了,但是我认为对于使用es6和jquery 2.2的人来说,这将是有益的。

I generally follow this (deferred approach) in my code

在我的代码中,我通常遵循这个(延迟的方法)。

sendAjaxRequest(URL, dataToSend) {
    return $.ajax({
        type        : 'POST',
        url         : URL,
        data        : JSON.stringify(dataToSend),
        dataType    : 'json'
    }).fail((responseData) => {
        if (responseData.responseCode) {
            console.error(responseData.responseCode);
        }
    });
},

I have attached a deferred fail method which will be called if some error occurs. It is an alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method in latest jquery.

我附上了一个延迟失败的方法,如果发生错误将被调用。它是错误回调选项的替代构造,.fail()方法替换了最新jquery中已弃用的.error()方法。

Next from the place of calling sendAjaxRequest I use then jquery promise callback

接下来是调用sendAjaxRequest,然后使用jquery承诺回调。

sendAjaxRequest(URL, dataToSend)
.then(
     (success) => {
     },
     (error) => {
     }
);

It will call success or error function based on the response received from server.

它将基于从服务器接收的响应调用success或error函数。

#1


24  

Personally, I have similar code to the following code in my library.

就我个人而言,我的库中有类似的代码。

$.ajaxSetup({
    error: function(xhr){
        alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
    }
});

jQuery docs Ajax/jQuery.ajaxSetup

jQuery Ajax / jQuery.ajaxSetup文档

The best way to bubble that error from the server side (using php) to the client side is to send a header through the Ajax request somewhere in the 400's (which is always associated with errors). Once the Ajax request receives this it will trigger your error function. This also means that you do not have to define an error: call in every $.ajax call.

将这个错误从服务器端(使用php)传递到客户端的最佳方式是通过Ajax请求在400的某个地方发送一个头部(这总是与错误相关)。一旦Ajax请求收到该请求,它将触发错误函数。这也意味着您不必定义一个错误:调用每一个$。ajax调用。

header('HTTP/1.0 419 Custom Error');

Quote from w3.org header information

引用w3.org头信息

Error 4xx, 5xx The 4xx codes are intended for cases in which the client seems to have erred, and the 5xx codes for the cases in which the server is aware that the server has erred. It is impossible to distinguish these cases in general, so the difference is only informational. The body section may contain a document describing the error in human readable form. The document is in MIME format, and may only be in text/plain, text/html or one for the formats specified as acceptable in the request.

错误4xx, 5xx 4xx代码用于客户端似乎有错误的情况,而5xx代码用于服务器知道服务器有错误的情况。一般情况下是无法区分这些情况的,所以这种差异只是信息上的。正文部分可以包含描述人类可读形式的错误的文档。该文档是MIME格式,并且只能是文本/纯文本、文本/html格式,或者是请求中指定的可接受格式。

#2


5  

$.ajax({
   type: "POST",
   url: "MyUrl",
   data: "val1=test",
   success: function(result){
        // Do stuff
   },
   error: function(request,status,errorThrown) {
        // There's been an error, do something with it!
        // Only use status and errorThrown.
        // Chances are request will not have anything in it.
   }
 });

#3


3  

Doesn't the jQuery ajax function accept one more parameter at the end, a callback for failed calls? If so, just add a fail:function(...){..} after the success callback.

jQuery ajax函数难道不接受最后的另一个参数——失败调用的回调吗?如果是这样,只需添加一个fail:function(…){.. .成功回调之后。

#4


0  

Return an error code on the server side using the HTTP error the best equates to what the error is. Then use the error callback. This will also allow you to show errors given by your webserver.

在服务器端使用HTTP错误返回错误代码,最好与错误的值相等。然后使用错误回调。这也允许您显示webserver给出的错误。

#5


0  

It's pretty late to answer this question but I think It will be beneficial to some one using es6 and jquery 2.2.

现在回答这个问题已经很晚了,但是我认为对于使用es6和jquery 2.2的人来说,这将是有益的。

I generally follow this (deferred approach) in my code

在我的代码中,我通常遵循这个(延迟的方法)。

sendAjaxRequest(URL, dataToSend) {
    return $.ajax({
        type        : 'POST',
        url         : URL,
        data        : JSON.stringify(dataToSend),
        dataType    : 'json'
    }).fail((responseData) => {
        if (responseData.responseCode) {
            console.error(responseData.responseCode);
        }
    });
},

I have attached a deferred fail method which will be called if some error occurs. It is an alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method in latest jquery.

我附上了一个延迟失败的方法,如果发生错误将被调用。它是错误回调选项的替代构造,.fail()方法替换了最新jquery中已弃用的.error()方法。

Next from the place of calling sendAjaxRequest I use then jquery promise callback

接下来是调用sendAjaxRequest,然后使用jquery承诺回调。

sendAjaxRequest(URL, dataToSend)
.then(
     (success) => {
     },
     (error) => {
     }
);

It will call success or error function based on the response received from server.

它将基于从服务器接收的响应调用success或error函数。