【问题标题】:Rest API axios error handling in redux-saga using catch使用 catch 在 redux-saga 中进行 Rest API axios 错误处理
【发布时间】:2019-08-28 13:55:31
【问题描述】:

在 Chrome.In 网络中检查时我得到响应

{"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() 上也会出错

【问题讨论】:

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


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 2018-09-08
    • 2020-05-13
    • 2019-06-14
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多