gpt4 book ai didi

javascript - 如何使用 Redux-Saga 处理 fetch() 响应中的错误?

转载 作者:行者123 更新时间:2023-12-03 12:13:41 24 4
gpt4 key购买 nike

我尝试处理 Unauthorized使用 redux-saga 的服务器出错。这是我的传奇:

function* logIn(action) {
try {
const user = yield call(Api.logIn, action);
yield put({type: types.LOG_IN_SUCCEEDED, user});
} catch (error) {
yield put({type: types.LOG_IN_FAILED, error});
}
}

我获取这样的数据:
fetchUser(action) {
const {username, password} = action.user;
const body = {username, password};
return fetch(LOGIN_URL, {
method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
})
.then(res => {
res.json().then(json => {
if (res.status >= 200 && res.status < 300) {
return json
} else {
throw res
}
})
})
.catch(error => {throw error});
}

但无论如何结果是 {type: 'LOG_IN_SUCCEEDED', user: undefined}当我期待 {type: 'LOG_IN_FAILED', error: 'Unauthorized'} .我的错误在哪里?如何使用 Redux-Saga 正确处理错误?

最佳答案

不要处理 thenerror在您的 fetchUser方法和你的传奇。既然你已经是 try/catch在你的传奇中,你可以在那里处理它。

例子

佐贺

function* logIn(action) {
try {
const response = yield call(Api.logIn, action);

if (response.status >= 200 && response.status < 300) {
const user = yield response.json();

yield put({ type: types.LOG_IN_SUCCEEDED, user });
} else {
throw response;
}
} catch (error) {
yield put({ type: types.LOG_IN_FAILED, error });
}
}

拿来
fetchUser(action) {
const { username, password } = action.user;
const body = { username, password };

return fetch(LOGIN_URL, {
method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
})
}

附带说明:我发现 fetch的 api 有点尴尬,因为它返回一个 then -当您提出请求时能够响应。那里有很多图书馆。我个人更喜欢 axios默认情况下返回 json。

关于javascript - 如何使用 Redux-Saga 处理 fetch() 响应中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007935/

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