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.