web-dev-qa-db-ja.com

エラー応答コードのグローバルaxios構成を設定する方法はありますか

私はreact/reduxアプリケーションでaxiosを使用しており、401、404などのエラーが発生した場合、axioを呼び出すときに各アクション関数でそれらに対処する必要があります。私はいくつかの一般的なイディオムでaxios呼び出しをラップしたaxios_config.jsを持っています。例えば:

// 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などを毎回処理する必要はありません。したがって、よりグローバルなスケールでそれらに対処できるようにする必要がありますが、サーバー側の検証エラーなど、リクエストに対する特定のエラーを処理する能力はまだあります。

14
Gregg

関数を受け入れ、catchが付加された関数を返す関数を作成してみることができます。オプションの2次引数を渡して、ローカルキャッチロジックを実行することもできます。

次に、これを単一のファイルに移動し、いつでもそこで変更できます。

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

お役に立てれば。

2
link

axios documentation のドキュメントとして、応答インターセプターを使用できます。

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

同じ議論を持つ他のスレッド

31
prasann shah