jQuery AJAX 错误处理(HTTP 状态代码)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12734714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:57:58  来源:igfitidea点击:

jQuery AJAX Error Handling (HTTP Status Codes)

jqueryajaxerror-handling

提问by FtDRbwLXw6

We have an API which uses proper HTTP status codes for errors, and responds with JSON-encoded responses and appropriate Content-Typeheader. My situation is that jQuery.ajax()triggers the errorcallback when it encounters an HTTP error status, and not the successcallback, so even when we have an intelligible JSON response, we have to resort to something like this:

我们有一个 API,它使用正确的 HTTP 状态代码来处理错误,并使用 JSON 编码的响应和适当的Content-Type标头进行响应。我的情况是当它遇到 HTTP 错误状态时jQuery.ajax()触发error回调,而不是success回调,所以即使我们有一个可理解的 JSON 响应,我们也必须求助于这样的事情:

$.ajax({
    // ...
    success: function(response) {
        if (response.success) {
            console.log('Success!');
            console.log(response.data);
        } else {
            console.log('Failure!');
            console.log(response.error);
        }
    },
    error: function(xhr, status, text) {
        var response = $.parseJSON(xhr.responseText);

        console.log('Failure!');

        if (response) {
            console.log(response.error);
        } else {
            // This would mean an invalid response from the server - maybe the site went down or whatever...
        }
    }
});

Is there a better paradigm than doing identical error handling in two spots in each jQuery.ajax()call? It's not very DRY, and I'm sure I've just missed something somewhere on good error handling practices in these cases.

有没有比在每次jQuery.ajax()调用中的两个点进行相同的错误处理更好的范例?它不是很枯燥,我敢肯定我只是在这些情况下错过了一些关于良好错误处理实践的东西。

回答by Terry

Check out jQuery.ajaxError()

查看 jQuery.ajaxError()

It catches global Ajax errors which you can handle in any number of ways:

它捕获全局 Ajax 错误,您可以通过多种方式处理这些错误:

if (jqXHR.status == 500) {
  // Server side error
} else if (jqXHR.status == 404) {
  // Not found
} else if {
    ...

Alternatively, you can create a global error handler object yourself and choose whether to call it:

或者,您可以自己创建一个全局错误处理程序对象并选择是否调用它:

function handleAjaxError(jqXHR, textStatus, errorThrown) {
    // do something
}

$.ajax({
    ...
    success: function() { ... },
    error: handleAjaxError
});