gpt4 book ai didi

javascript - 获取 : Reject promise with JSON error object

转载 作者:行者123 更新时间:2023-12-02 16:21:54 25 4
gpt4 key购买 nike

我有一个 HTTP API,它会在成功和失败时返回 JSON 数据。

失败示例如下所示:

~ ◆ http get http://localhost:5000/api/isbn/2266202022 
HTTP/1.1 400 BAD REQUEST
Content-Length: 171
Content-Type: application/json
Server: TornadoServer/4.0

{
"message": "There was an issue with at least some of the supplied values.",
"payload": {
"isbn": "Could not find match for ISBN."
},
"type": "validation"
}

我想在 JavaScript 代码中实现如下所示:

fetch(url)
.then((resp) => {
if (resp.status >= 200 && resp.status < 300) {
return resp.json();
} else {
// This does not work, since the Promise returned by `json()` is never fulfilled
return Promise.reject(resp.json());
}
})
.catch((error) => {
// Do something with the error object
}

最佳答案

 // This does not work, since the Promise returned by `json()` is never fulfilled
return Promise.reject(resp.json());

好吧,resp.json promise 将会被履行,只是Promise.reject不等待它并立即拒绝>有一个 promise

我假设您更愿意执行以下操作:

fetch(url).then((resp) => {
let json = resp.json(); // there's always a body
if (resp.status >= 200 && resp.status < 300) {
return json;
} else {
return json.then(Promise.reject.bind(Promise));
}
})

(或者明确写出)

    return json.then(err => {throw err;});

关于javascript - 获取 : Reject promise with JSON error object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39994887/

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