定义全局错误处理程序时跳过$ .ajax()。fail()

时间:2018-04-30 18:40:13

标签: jquery ajax promise

我正在为状态代码500定义一个全局jQuery错误处理程序(当重试耗尽时,重试机制带有一些消息)。我想覆盖可能已添加到.fail()请求的任何$.ajax承诺。我的代码如下:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
        <script type="text/javascript">

            function call() {

                $.ajax({
                  url: '/rest/api/v1/some_errorneous_parth',
                  retryCount:3,
                  method: 'GET'
                }).done(function(data){
                    console.log(data);
                }).fail(function() {
                    console.log("should not print");
                });
            }

            $(document).ready(function () {
                $.ajaxSetup({
                    retryCount: 3,
                    error: function retry(response) {
                        if(response.statuscode === 500) {
                            if(--this.retryCount){
                                $.ajax(this);
                            }
                            else {
                                console.log("sorry, i've 'tried everything");
                            }
                        }
                    }
                });
            });
        </script>
    </head>
    <body>
        <input type="button" onclick="call()" value="submit"/>
    </body>
</html> 

如果服务器返回500,我将不会打印should not print,直到重试计数用完为止。

1 个答案:

答案 0 :(得分:1)

一些观察......

jQuery文档说的是.ajaxSetup()

  

...我们强烈建议不要使用此API。

文档还说:

  

使用任何函数的所有后续Ajax调用都将使用新设置,除非被单个调用覆盖,直到下一次调用$ .ajaxSetup()。

因此,您期望在ajaxSetup中建立的相应选项覆盖$ .ajax请求中的选项是从前到后的。覆盖是相反的。

在任何情况下,.done().fail()选项都不遵守“被个别电话覆盖”规则。在ajaxSetup中建立的失败回调和在单个调用中建立的失败回调将(在出错时)按此顺序激活。该文档没有提供任何关于此的警告。

retryCount等任意选项将被忽略。

重试需要通过其他方式进行编排 - 请参阅例如Promise Retry Design Patterns