使用 catch 处理 redux-saga 中的 Rest API axios 错误 [英] Rest API axios error handling in redux-saga using catch

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

问题描述

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

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

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 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆