首页 > 解决方案 > Redux Saga 发生错误时获取 axios 响应对象

问题描述

这对我来说是新的,我试图弄清楚当 axios 使用 yield generator (redux-saga) 发生错误时如何检索请求正文

这是我正在使用的一段代码:

function requestLogin(user: ILoginUserPayload) {
  const loginUrl = `${config.apiUrl}/auth/logIn`;
  return axios.post(loginUrl, user);
}

export default function* watchAuthAction(): IterableIterator<any> {
  while (true) {
    const { payload }: { payload: ILoginUserPayload} = yield take(TYPES.LOGIN_REQUEST);

    console.log(`Payload`, payload);
    try {
      const response = yield requestLogin(payload);
      console.log(`Response`, response);
    } catch (error) {
      // According to my debug, error.request contains all the axios info
      console.log(error.request.response);
      yield put({ type: TYPES.LOGIN_FAILURE, error: error.request.response.message });
    }
  }
}

我用VSCode调试了错误内容,我发现它有axios请求信息(我的意思是,我99%确定axios会抛出错误,它就来了)

我的身体反应是这样的:

{"message":"User doesn't exist","stack":"Error: User doesn't exist"}

所以我试着用:

console.log(error.request.response.message);

但是不行,可能是我忘记了关于axios的一些事情……

任何想法?

编辑:我实际上正在阅读这部分:https ://github.com/axios/axios#handling-errors 但我仍然无法访问我的数据:/

标签: reactjserror-handlingaxiosredux-saga

解决方案


您的代码似乎是正确的,对我来说唯一的区别是:

try {
    const response = yield call(apiCall, action.payload)
      yield put({ type: successReducer, payload: response });
  } catch(error) {
    // Construct an error message
    let errorMessage = error.response.status + ":"+ error.response.statusText;
    yield put({ type: failReducer, payload: {  message : errorMessage }});
  }

所以对我来说,区别似乎是我访问error.response.status而不是error.request.response。


推荐阅读