【问题标题】:Is there a way to set global axios config for error response codes有没有办法为错误响应代码设置全局 axios 配置
【发布时间】:2017-02-23 00:53:52
【问题描述】:

我在我的 react/redux 应用程序中使用axios,当我遇到 401、404 等错误时,我目前在调用 axios 时必须为每个操作函数处理它们。我有一个 axios_config.js,其中我用一些常见的习语包装了 axios 调用。例如:

// need to move this to app config
const BASE_URL = 'http://localhost:8080/api/';

function config() {
  return {
    headers: {'X-Token-Auth': localStorage.getItem('token')}
  }
}

export function fetchData(url) {
  return axios.get(`${BASE_URL}${url}`, config());
};

我正在苦苦挣扎的是常见的错误,如 401、404 等。目前,我正在这样做:

export function fetchBrands() {
  return function(dispatch) {
    dispatch({type:FETCHING_BRANDS});

    fetchData('brands')
      .then(response => {
        dispatch({
          type: FETCH_BRANDS_SUCCESS,
          payload: response
        });
      })
      .catch(err => {
        // deal with errors
      });
  }
}

但在 catch 块中,我不想每次都处理 401、404 等。因此,我需要能够在更全局的范围内处理这些问题,但仍然能够处理请求的特定错误,例如服务器端验证错误。

【问题讨论】:

    标签: reactjs redux react-redux axios


    【解决方案1】:

    您可以尝试编写一个函数,该函数接受一个函数并返回附加了一个 catch 的函数。您甚至可以传递一个可选的辅助参数来执行本地捕获逻辑。

    然后可以将其移动到单个文件中,您可以随时修改它。

    export function fetchBrand(id) {
      return function (dispatch) {
        wrapCatch(
          fetchData(`brands/${id}`)
            .then(response => {
              dispatch({
                type: FETCH_BRAND_SUCCESS,
                payload: response
              });
            }),
          function (err) {
            // deal with errors
          }
        );
      }
    }
      
    export function wrapCatch(f, localErrors) {
      return f.catch(err => {
          // deal with errors
          localErrors();
      });
    }

    希望这会有所帮助。

    【讨论】:

    • 谢谢,我今天就试一试,看看效果如何。
    • 我进行了一些编辑,因为您的代码不太正确,但要点已经足够了。标记为正确答案,因为它确实解决了问题,但是,我觉得他们的处理方式稍微优雅一些​​。仍然需要最终用户对错误处理有太多了解。
    • @link 让你在这里传递的不是函数,而是请求对象。函数似乎在这里具有误导性。
    【解决方案2】:

    您可以将响应拦截器用作axios documentation 中的文档。

    axios.interceptors.response.use(undefined, function (error) {
        if(error.response.status === 401) {
          ipcRenderer.send('response-unauthenticated');
          return Promise.reject(error);
        }
      });

    other thread with same discussion

    【讨论】:

    • 这是否记录在 axios 网站的某个地方?
    • 它有效。最好总是返回Promise.reject(error)
    • 请注意,这在捕获之前运行,因此,它不是丢失捕获或捕获未处理错误的后备。
    猜你喜欢
    • 2021-01-04
    • 2015-09-27
    • 2011-03-19
    • 2014-07-04
    • 1970-01-01
    • 2021-04-28
    • 2012-02-16
    • 1970-01-01
    相关资源
    最近更新 更多