redux-saga catch 加载资源失败:net::ERR_CONNECTION_REFUSED

redux-saga catch Failed to load resource: net::ERR_CONNECTION_REFUSED

我使用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);
}

问题: 当后端服务器宕机时。它不会 return 任何错误返回给我。浏览器会报错 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

如果您将 try/catch 放在 axios 请求本身周围,那么您可以更详细地了解原因。

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

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

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