当axios ajax调用失败时如何访问状态代码

时间:2018-09-27 16:05:56

标签: ajax reactjs react-redux axios http-status-codes

在我们的项目中,我们使用Axios中间件来进行Ajax调用,并且为了具有一致的Action类型,我们在数据结构中使用FSA(Flux标准操作)。例如,我们的Actions和Reducer外观如​​下

//Action
 import { createAction } from "typesafe-actions";

 export const GET_USER = "GET_USER";

 // GET_USER_SUCCESS and GET_USER_FAILURE are automatically triggered from the axios 
    middleware
export const userActions = {
    getUser: createAction(GET_USER, () => ({
        type: GET_USER,
        payload: {
        request: {
            url: "/username",
        },
    },
  })),
getUserSuccess: createAction("GET_USER_SUCCESS", (data: string) => ({
    type: "GET_USER_SUCCESS",
    payload: {
        data: data // put returned data type here name: "nothing",},
    },
})),
getUserFailure: createAction("GET_USER_FAILURE"),
};

//Redux
import { RootAction } from "../actions/RootAction";
import { userActions } from "../actions/UserActions";
import { getType } from "typesafe-actions";

export const userReducer = (state = INITIAL_STATE, action: RootAction): UserState => 
{
    switch (action.type) {
        case getType(userActions.getUserSuccess): {
            return {
                ...state,
                username: action.payload.data,
            };
        }
    default:
        return state;
    }
};

现在,如果出现呼叫失败,我想从下面访问状态代码 enter image description here

需要有关如何在操作或减速器或应用程序中的任何位置访问状态代码的帮助。

1 个答案:

答案 0 :(得分:0)

您可以在操作文件中创建错误处理功能,并使用它来分派具有错误详细信息的操作。然后只需将此函数放在每个 catch 语句中,从而访问应用程序中任何位置的错误。示例实现如下所示(redux thunk方法):

获取数据

export function fetchData() {
  return async (dispatch) => {
    try {
      const { data: payload } = await axios.get('https://jsonplaceholder.typicode.com/psosts');
      dispatch({
        type: FETCH_DATA,
        payload
      })
    } catch (error) { throwError(error, dispatch) }
  }
}

处理错误

function throwError(error, dispatch) {
  const { status, statusText } = error.response;
  dispatch({
    type: THROW_ERROR,
    payload: { status, content: statusText }
  })
}

一个减速器就像其他减速器一样;)