[英]How do I catch an error message from JSON fetch response?
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. 我想要做的是捕获错误消息,并从JSON响应中获取错误消息。 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. 我希望在我的第二个console.log中的表单上得到响应,但是以某种方式在第一个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? 另外,即使API密钥不存在,为什么响应在第一个实例中仍给我“确定”?
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? 当响应应该已经是JSON格式时,为什么还要在第二个实例中返回rsp.json()以获得正确的JSON?
The rsp
in the first then-block is a response object, not the data returned by the backend. 第一个then块中的rsp
是响应对象,而不是后端返回的数据。 The response object doesn't have a stat
field, so the value of it cannot be "ok". 响应对象没有stat
字段,因此其值不能为“ ok”。 You should probably check for rsp.ok
or rsp.status
instead. 您可能应该改为检查rsp.ok
或rsp.status
。
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. 在第二个then块中,您可以根据后端返回的JSON数据进行一些检查,然后根据需要引发错误。
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.