在反应中读取错误对象

时间:2017-12-15 21:49:24

标签: ajax reactjs action

我正在进行AJAX调用,当它成功时我可以读取API返回的响应,但是当出现错误时,我只从服务器获取错误,而不是消息

这是我的行动代码

export const updateUsersAction = (id) => {
  return (dispatch) => {
    dispatch(beginRequest());
    return updateUsers(id)
      .then(response => {
        dispatch(updateUsersSuccess());
        return response.data;
      })
      .catch(error => {
        dispatch(defaultError(error));
        throw (error);
      });
  };
};

找不到ID时服务器的错误是#400,但是有一条特定的消息

{
    "error_message": "The id for this team was not found"    
}

如何阅读error_message?谢谢

export const updateUsers = function(id) {

  return axios.post(
    `/api/update_users/`,
    {
      id: id
    }
  );
};

1 个答案:

答案 0 :(得分:0)

错误JSON可以在error.response.data上找到,在这种情况下是error.response.data.error_message

参考https://github.com/axios/axios#handling-errors