如何使用 Redux-Saga 处理 fetch() 响应中的错误? [英] How to handle errors in fetch() responses with Redux-Saga?

查看:23
本文介绍了如何使用 Redux-Saga 处理 fetch() 响应中的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 redux-saga 处理来自服务器的 Unauthorized 错误.这是我的传奇:

I try to handle Unauthorized error from server using redux-saga. This is my 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 处理错误?

But anyway result is {type: 'LOG_IN_SUCCEEDED', user: undefined} when I expect {type: 'LOG_IN_FAILED', error: 'Unauthorized'}. Where is my mistake? How to handle errors right using Redux-Saga?

推荐答案

不要在 fetchUser 方法中处理 thenerror和你的传奇.由于您已经try/catch在您的传奇中,您可以在那里处理它.

Don't handle the then and error in your fetchUser method and your saga. Since you are already try/catching in your saga, you could handle it there.

传奇

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.

As a side note: I find fetch's api a little awkward because it returns a then-able response when you make a request. There are many libraries out there; personally I prefer axios which returns json by default.

这篇关于如何使用 Redux-Saga 处理 fetch() 响应中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆