我尝试处理 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 正确处理错误?
最佳答案
不要处理 then
和 error
在您的 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/