本文介绍了使用catch在Redux-Saga中处理Rest API axios错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On inspecting in Chrome.In network i get response

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

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

Is there any issue in catching axios error.HOw should i handle this issue.I get succesfull response on authorised login.

Redux-Saga生成器功能

Redux-Saga Generator function

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

also gets an error on axios.post()

推荐答案

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

这是文档

这篇关于使用catch在Redux-Saga中处理Rest API axios错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:55