Javascript 如何从JSON fetch响应捕获错误消息?
考虑以下代码:Javascript 如何从JSON fetch响应捕获错误消息?,javascript,json,fetch-api,Javascript,Json,Fetch Api,考虑以下代码: 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 "
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);
});
我想做的是用我应该从JSON响应中得到的错误消息捕获一个错误。我希望在第二个console.log中看到的表单上得到响应,但不知何故,响应与第一个console.log中的不一样。首先,我如何获得我想要的响应
另外,为什么响应在第一个实例中给我“ok”,即使API键不存在
为什么我必须返回rsp.json()才能在第二个实例中获得正确的json,而响应应该已经是json格式的?第一个then块中的
rsp
是一个响应对象,而不是后端返回的数据。响应对象没有stat
字段,因此其值不能为“ok”。您可能应该检查rsp.ok
或rsp.status
检查
在第二个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);
});