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

时间:2019-08-28 13:55:31

标签: reactjs redux error-handling axios redux-saga

在Chrome中进行检查。在网络中,我得到了答复

{"status":"error","data":{"message":"Unauthorized"}} 

捕获axios错误是否有任何问题。我应该如何处理此问题。 授权登录后,我会获得成功的答复。


Redux-Saga Generator函数


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()上也出现错误

1 个答案:

答案 0 :(得分:2)

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 })
}

这是Documentation