gpt4 book ai didi

javascript - 如何从 JSON 提取响应中捕获错误消息?

转载 作者:行者123 更新时间:2023-11-30 14:26:55 28 4
gpt4 key购买 nike

考虑下面的代码:

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 中的不同。如何在第一时间获得我想要的响应?

此外,即使 API key 不存在,为什么响应一开始就给我“ok”?

当响应应该已经是 JSON 格式时,为什么我必须返回 rsp.json() 才能在第二个实例中获得正确的 JSON?

最佳答案

第一个then block 中的rsp是一个response对象,不是后端返回的数据。响应对象没有 stat 字段,因此它的值不能是“ok”。您可能应该检查 rsp.okrsp.status

检查 response object reference

在第二个 then-block 中,您可以根据后端返回的 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);
});

关于javascript - 如何从 JSON 提取响应中捕获错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51785621/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com