gpt4 book ai didi

javascript - 使用 fetch 和 ES6 promise 处理自定义错误的最简洁方法

转载 作者:数据小太阳 更新时间:2023-10-29 04:01:25 28 4
gpt4 key购买 nike

我正在尝试使用 fetch 和 ES6 promises 智能地处理来 self 们 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。

此外,为了阐明 checkStatuscheckErrorStatus 做了类似的事情:

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
}
}

有什么清理的建议吗?

最佳答案

我想你可以很容易地把它写出来:

fetch(…).then(response => {
if (response.ok)
return response[response.status == 204 ? "text" : "json"]();
if (response.status == 422)
return response.json().then(err => { throw err; });
if (response.status == 406)
var error = new AuthentificationError(response.statusText); // or whatever
else
var error = new Error(response.statusText)
error.response = response
throw error;
})

关于javascript - 使用 fetch 和 ES6 promise 处理自定义错误的最简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33907465/

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