在redux-saga中使用catch处理Rest API axios错误

3
在Chrome中检查时,在网络中获取响应。
{"status":"error","data":{"message":"Unauthorized"}} 

在捕获axios错误方面是否存在问题?我该如何处理这个问题。我已经在授权登录后成功收到了响应。


Redux-Saga生成器函数


export function* loginUserSaga(action) {
  yield put(actions.loginStart());
  const loginData = {
    'email': action.email,
    'password': action.password
  };
  let url ="api/v1/login";
  console.log("Saga-send:",loginData);
  try {
    const response = yield axios.post(url, loginData);
    console.log("Saga-recived:",response);
    yield localStorage.setItem("token", response.data.data.access_token);
    yield put(
      actions.loginSuccess(response.data.idToken)
    );
  } catch (error) {
    console.log("Saga-error:",error);  
    yield put(actions.loginFail(error));
  }
}

控制台


Saga-send: {email: "123456@gmail.com", password: "assasaassasa"} 
Saga-error: Error: Request failed with status code 401
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)

axios.post()也会出现错误。


3
我认为你需要使用console.log("Saga-error:",error.response); 进行调试。请查看此讨论 https://github.com/axios/axios/issues/960 - Dario
1个回答

3
import Api from './path/to/api'
import { call, put } from 'redux-saga/effects'

function fetchProductsApi() {
  return Api.fetch('/products')
    .then(response => ({ response }))
    .catch(error => ({ error }))
}

function* fetchProducts() {
  const { response, error } = yield call(fetchProductsApi)
  if (response)
    yield put({ type: 'PRODUCTS_RECEIVED', products: response })
  else
    yield put({ type: 'PRODUCTS_REQUEST_FAILED', error })
}

这里是文档

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接