rel*_*l1x 20 javascript fetch redux redux-saga
我尝试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});
}
}
Run Code Online (Sandbox Code Playgroud)
我获取这样的数据:
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});
}
Run Code Online (Sandbox Code Playgroud)
但无论如何,结果是{type: 'LOG_IN_SUCCEEDED', user: undefined}我期待的结果{type: 'LOG_IN_FAILED', error: 'Unauthorized'}.我的错误在哪里?如何使用Redux-Saga正确处理错误?
Mar*_*cke 22
不处理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 });
}
}
Run Code Online (Sandbox Code Playgroud)
取
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)
})
}
Run Code Online (Sandbox Code Playgroud)
作为旁注:我发现fetchapi有点尴尬,因为它then在你提出请求时会返回一个-able响应.那里有很多图书馆; 我个人更喜欢axios默认返回json.
| 归档时间: |
|
| 查看次数: |
12707 次 |
| 最近记录: |