1đź‘Ť
It seems like bad API design to return a “no response found” as HTTP 200, but if you have no control over the API, you’ll just have to handle that in your success function.
Put your error handling code in a function and call it accordingly:
fetchData: function(name){
var self = this;
self.$http.get('http://www.apiservice.com/', {
params: {
city: name
},
}).then((response) => {
// success callback
if (response.Response === "False") {
onError(response)
} else {
toastr.success('Success!');
console.debug(response);
}
}, onError);
}
function onError(response) {
toastr.error('Something went wrong!')
}
👤Ayush
1đź‘Ť
You can use promise chaining to switch a promise from resolve to reject:
fetchData: function(name){
var self = this;
self.$http.get('http://www.apiservice.com/', {
params: {
city: name
},
}).then(response)=>{
if(response.Response === "False"){
return Promise.reject(response)
}else{
return response
}
},(a)=>a).then((response) => {
// success callback
toastr.success('Success!');
console.debug(response);
}, (response) => {
// error
toastr.error('Something went wrong!')
});
}
The important part is this:
then(response)=>{
if(response.Response === "False"){
return Promise.reject(response)
}else{
return response
}
},(a)=>a)
so if the response is valid, and the data contains Response: "False"
we return a rejected promise, otherwise we just return the response data, which is then wrapped in a resolved promise, after that the next then
executes as before, but invalid data has already been rejected.
👤Euan Rochester
Source:stackexchange.com