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

问题描述 投票:0回答:1

在 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: "[email protected]", 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个回答
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 })
}

这是文档

© www.soinside.com 2019 - 2024. All rights reserved.