Home > Software design >  jQuery Exception Handling and catch block
jQuery Exception Handling and catch block

Time:12-31

I am attempting to deal with errors that are returned by an API I am calling by jQuery.ajax().

If the error has an HTTP Status >= 500, I want to do some specific actions, otherwise I want to leave it to the calling routine to handle the exception.

So - I have code that looks like this :

        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");
        });
    }

Where deleteViaApi looks like this :

    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;
                        }
                    }
                }));
            });
        });
};

What I find is that, when the API returns an error in the 500 range, the error handler is called as I expect, and the error_message function is also called. But, I also find that the catch code in deleteClient is also executed. I don't want this to happen, but I can't work out why it's happening, or how to stop it from happening.

CodePudding user response:

Avoid the Promise constructor antipattern! And don't use an error handler, which will be ignored for promise purposes, use .catch() instead.

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;
            }
        });
    });
}
  • Related