The scenario is as following:
- a call is made to the server that returns an array of objects if everything is fine.
- if an error occurs on the server, it returns a json that contains an error message.
Out of this scenario, I want to create a function that returns a promise, which I can use like this from a client:
initData()
.done(function(myArray) {
processData(myArray);
})
.fail(function(response) {
console.log("An error occured: " + response.errorMessage);
});
The client should not care that initData() makes a call to a server, it should get the fail() called for both ajax call failures or server specific errors.
For this I need two things:
- Hide the failure of the server call and create a new error message object.
- Make the promise fail if the call to the server returned with an error message object.
Here's what I have:
function initData() {
var promise = $.getJSON(url);
return promise.then(function(response) {
if (typeof response !== 'undefined' && response !== null && typeof response.errorMessage !== 'undefined') {
// Do something to trigger fail() in the client caller.
}
return response;
}, function(resp) {
// This satisfies point 1 above.
return { errorMessage: "Server error." };
});
}
How may I satisfy the second requirement? I'm using jquery 3.1.1.
Thanks.