LoginSignup
16
15

More than 1 year has passed since last update.

【Javascript】axiosエラーハンドリング共通化を考えてみた

Last updated at Posted at 2021-06-20

Vue.jsの開発で非同期通信にaxiosを使用している。
非同期通信時のエラーハンドリングのロジック自体は同じで、各axios実装箇所で行っていた。

開発の効率や、ソースコードの可読性、後々メンテナンス、拡張などを考えた時のために共通化を考えてみた。

axios実装のビフォーアフター

Before

【既存のaxios実装】
axiosの各呼び出し箇所で下記のようなエラーハンドリングしており、同じロジックコードが散在している。

axios.post(url, params)
  .then(response => {
          // 成功時の処理
  }).catch(error => {
      // 失敗時の処理
      switch (error.response?.status) {
        case 401:
        // HTTPステータスに応じて処理
        case 403:
        default:
        // 例外処理
      }
 });

After

【エラーハンドリングの共通化後のaxios実装】
エラーハンドリングを共通化したことでaxiosの各呼び出し箇所では成功時の処理のみを実装する。
ソースコードがスッキリした!!

const response = axios.post(url, params);
if(response) {
 // 成功時の処理(エラー時は共通コードでハンドリングされるため、responseが返らない)
}

axiosのエラーハンドリング共通化

axiosAPIのInterceptorsを活用する。

Interceptorsについてはこちら参照:Interceptors | axios公式

  • Interceptorsを使って、axiosのエラーハンドリングを共通化
axiosErrorHandler.js
axios.interceptors.response.use(function (response) {
    // 成功時の処理
    return response;
  }, function (error) {
    // 失敗時の処理
    switch (error.response?.status) {
       case 401:
       // HTTPステータスに応じて処理
       case 403:
       default:
       // 例外処理  
    }
  });

ちなみにInterceptorsはaxiosのrequest前処理も共通化することができる:bulb:

Nuxt.jsを使っていたらpluginが用意されているのでそちらを使用するのが良さそうです:ok_hand:
nuxt/axios

Vue.jsでのエラーハンドリングについて、ご意見や事例があればぜひお聞かせください:bow:

16
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
15