Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
102
rated 0 times [  104] [ 2]  / answers: 1 / hits: 12603  / 6 Years ago, fri, august 10, 2018, 12:00:00

Consider the code below:



fetch('https://api.flickr.com/services/rest/?method=flickr.photos.search' +
'&api_key=thiskeyshouldgivemeanerror&text=dog&format=json' +
'&per_page=24&nojsoncallback=1')
.then(function(rsp) {
// Gives Response {type: cors, url: https://api.flickr.com/services/rest/
// ?method=flick…text=dog&format=json&per_page=24&nojsoncallback=1,
// redirected: false, status: 200, ok: true, …}
console.log(rsp);
if(rsp.stat !== ok) {
throw new Error(rsp.message);
}
else {
return rsp.json();
}
})
.then(function(rsp) {
// Gives {stat: fail, code: 100, message: Invalid API Key (Key not found)}
// if no error is thrown.
// Exactly what I want in the first instance!
console.log(rsp);
})
.catch(function(err) {
alert(Something went wrong. + err);
});


What I want to do is to catch an error with the error message I should get from the JSON response. I expect to get a response on the form it looks in my second console.log, but somehow the response does not look like that in the first console.log. How do I get the response I want in the first instance?



Also, why does the response give me ok in the first instance, even though the API key does not exist?



And why do I have to return rsp.json() to get the correct JSON in the second instance when the response should already be in JSON format?


More From » json

 Answers
1

The rsp in the first then-block is a response object, not the data returned by the backend. The response object doesn't have a stat field, so the value of it cannot be ok. You should probably check for rsp.ok or rsp.status instead.



Check response object reference



In the second then-block you could do some checks based on the JSON data returned by the backend, and then throw an error if needed.



fetch(url)
.then(function(response) {
if(!response.ok) {
throw new Error(not ok);
}
return response.json()
})
.then(function(result) {
if(result.stat === fail) {
throw new Error(result.message);
}

// Everything should be ok, process the result here

})
.catch(function(err) {
alert(err);
});

[#11902] Wednesday, August 8, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jovanymarshalld

Total Points: 676
Total Questions: 94
Total Answers: 81

Location: Thailand
Member since Thu, Apr 22, 2021
3 Years ago
;