redux-saga catch无法加载资源:net :: ERR_CONNECTION_REFUSED

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

我使用axios来调用后端服务器。使用redux-saga,我可以轻松控制服务器的副作用。

import {call, put, takeEvery} from "redux-saga/effects";
import {REQUEST_FAILED, REQUEST_SUCCESS, ROOT_URL, SUBMIT_USERNAME_PASSWORD} from "../../constants";
import axios from "axios/index";

const shootApiTokenAuth = (values) => {
  const {username, password} = values;
  return axios.post(`${ROOT_URL}/api-token-auth/`,
    {username, password});
};

function* shootAPI(action) {
  try {
    const res = yield call(shootApiTokenAuth, action.payload);
    const {history} = action.payload;
    yield put({
      type: REQUEST_SUCCESS,
      payload: res
    });
    history.push('/companies'); //push user to `/companies` page
  } catch (err) {
    yield put({
      type: REQUEST_FAILED,
      payload: err
    });
  }
}

export function* watchSubmitBtn() {
  yield takeEvery(SUBMIT_USERNAME_PASSWORD, shootAPI);
}

问题:后端服务器关闭时。它不会将任何错误返回给我。并且浏览器会引发错误Failed to load resource: net::ERR_CONNECTION_REFUSED

我在callback method上看过以前的答案,但我更喜欢axiosredux-saga而不是callback

我曾尝试过console.log(err)。我仍在搜索它们以获取错误消息并将其与服务器响应错误区分开来。

Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:87)

题: 我如何使用axiosredux-saga来捕捉err

javascript reactjs axios redux-saga
2个回答
0
投票

如果你把try / catch放在axios请求本身,那么你可以在原因上获得更多的粒度。

https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253

您可能希望有一个自定义错误格式和一个错误减少器,可以处理适当的不同类型的错误。例如,如果你有一个响应,你可以解析它并将其添加到错误中,否则你知道有一个应用程序级别错误,你将使用'糟糕'页面或类似的东西处理。


0
投票
case REQUEST_FAILED:
      //Probably it can failed by 2 reason
      //1. 404 from server
      //2. network is down
      if (action.payload.response === undefined) {
        return {
          token: undefined,
          message: 'Network is down',
          isAuthenticated: false,
          statusCode: 406
        }
      } else {
        const tmp = action.payload.response.request.response;
        const tmp2 = JSON.parse(tmp);
        return {
          token: undefined,
          message: tmp2.non_field_errors[0],
          isAuthenticated: false,
          statusCode: action.payload.response.status
        };
      }
© www.soinside.com 2019 - 2024. All rights reserved.