Reputation: 1309
I have this VUEJS / VUEJS Resources snippet that is fetching data from an API service.
fetchData: function(name){
var self = this;
self.$http.get('http://www.apiservice.com/', {
params: {
city: name
},
}).then((response) => {
// success callback
toastr.success('Success!');
console.debug(response);
}, (response) => {
// error
toastr.error('Something went wrong!')
});
}
And it will always return a 200 OK response... So i don't really know how to show the toastr.error
, if its always a "success".
The false response looks like this: {Response: "False", Error: "City not found!"}
.
How can I fetch the false
in the Response of a 200 ok return, and throw an error?
Upvotes: 0
Views: 993
Reputation: 183
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.
Upvotes: 1
Reputation: 42450
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!')
}
Upvotes: 1