我有一个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"
}
Run Code Online (Sandbox Code Playgroud)
我想在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()); …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用fetch和ES6 promises智能地处理来自API的成功/错误响应.
以下是我需要处理响应状态的方法:
204: has no json response, but need to treat as success
406: should redirect to sign in
422: has json for error message
< 400 (but not 204): success, will have json
>= 400 (but not 422): error, will not have json
Run Code Online (Sandbox Code Playgroud)
所以,我正在努力学习如何干净利落地写这个.
我现在有一些不太常用的代码,看起来像这样:
fetch()
.then(response => checkStatus(response))
.then(parseJSON) //will throw for the 204
.then(data => notify('success', someMsg))
.catch(error => checkErrorStatus(error))
.then(parseJSON)
.then(data => notify('error', dataForMsg)
.catch(error => notify('error', someGenericErrorMsg)
Run Code Online (Sandbox Code Playgroud)
但是使用catch两次似乎很奇怪,我还不知道如何处理204.
另外,只是澄清checkStatus并checkErrorStatus做类似的事情:
export …Run Code Online (Sandbox Code Playgroud)