jQuery 异常处理和 catch 块

jQuery Exception Handling and catch block

我正在尝试处理 API 我通过 jQuery.ajax() 调用返回的错误。

如果错误的 HTTP 状态 >= 500,我想做一些特定的操作,否则我想将其留给调用例程来处理异常。

所以 - 我的代码如下所示:

        function deleteClient() {
        $('#deleteclienterrorpara').css('visibility', 'hidden');

        utils.deleteViaApi("/api/client/v1/client/" + ns.currentClientId)
        .then(function () {
            utils.closeModal("#clientMaintenance","/#/locateclient");
            utils.showInformationMessage("child deleted successfully");
        })
        .catch(function(error){

            $('#deleteclienterror').text(error.responseJSON.error.message);
            $('#deleteclienterrorpara').css('visibility', 'visible');
            $("#deleteclienterrorpara").addClass("error");
        });
    }

deleteViaApi 看起来像这样:

    const deleteViaApi = function(url){
    let contextDetails = setUpContextDetails(url,"DELETE");
        return new Promise(function(resolve, reject) {
            firebase.auth().currentUser.getIdToken()
                .then(function(idToken) {
                    return {'Authorization': 'Bearer ' + idToken,
                        'ACTING_ON_BEHALF_OF' : ns.actingAs};
                }).then(function(headers) {
                resolve ($.ajax({
                    url: url,
                    type: "DELETE",
                    headers: headers,
                    complete: function(data) {
                        console.log("DELETE at " + url + " completes");
                    },
                    error: function(jqXHR,textStatus,errorThrown){
                        if (jqXHR.statusCode().status >= 500 ) {
                            return error_message(textStatus, errorThrown, jqXHR, contextDetails);
                        } else {
                            throw errorThrown;
                        }
                    }
                }));
            });
        });
};

我发现,当 API returns 出现 500 范围内的错误时,error 处理程序如我所料被调用,而 error_message函数也被调用。但是,我还发现 deleteClient 中的 catch 代码也被执行了。我不希望这种情况发生,但我不知道为什么会发生,或者如何阻止它发生。

避开Promise constructor antipattern!并且不要使用 error 处理程序,它会出于 promise 的目的而被忽略,请改用 .catch()

function deleteViaApi(url) {
    let contextDetails = setUpContextDetails(url,"DELETE");
    return firebase.auth().currentUser.getIdToken().then(function(idToken) {
        return {
            'Authorization': 'Bearer ' + idToken,
            'ACTING_ON_BEHALF_OF' : ns.actingAs
        };
    }).then(function(headers) {
        return new Promise((resolve, reject) => {
//      ^^^^^^
            $.ajax({
                url: url,
                type: "DELETE",
                headers: headers,
                success: resolve,
                error(jqXHR,textStatus,errorThrown) {
                    reject({jqXHR,textStatus,errorThrown});
                }
            });
        }).finally(function() {
            console.log("DELETE at " + url + " completes");
        }).catch(function({jqXHR,textStatus,errorThrown}){
            if (jqXHR.statusCode().status >= 500 ) {
                return error_message(textStatus, errorThrown, jqXHR, contextDetails);
            } else {
                throw errorThrown;
            }
        });
    });
}