【发布时间】:2016-02-27 17:01:19
【问题描述】:
我正在尝试使用 fetch 和 ES6 承诺智能地处理来自我们 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
所以,我正在为如何干净利落地写这个而苦苦挣扎。
我现在有一些不太出色的代码,看起来像这样:
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)
但是使用两次 catch 似乎很奇怪,我还不知道如何处理那个 204。
另外,为了澄清 checkStatus 和 checkErrorStatus 做类似的事情:
export function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response
} else {
let error = new Error(response.statusText)
error.response = response
throw error
}
}
function checkErrorStatus(error) {
if(error.response.status === 422) {
return error.response
} else {
let error = new Error(response.statusText)
error.response = response
throw error
}
}
对清理这个有什么建议吗?
【问题讨论】:
-
哦,就这么简单:export function parseJSON(response) { return response.json() }
-
对于
422的情况,请参阅this question -
“”是什么意思?
-
好吧,来自服务器的状态为 422 的响应将包含一些 JSON,其中包含我用来在错误通知中显示的验证错误消息之类的内容。但是所有其他 400 都没有那个 json。他们需要区别对待。
-
我的意思是它应该是 "" 和 ">= 400 (but not 422): error, no json "
标签: javascript promise ecmascript-6 es6-promise fetch-api