LoginSignup
6
4

More than 3 years have passed since last update.

axiosでエラーになった時のリトライ処理をinterceptorsで実行する

Posted at

TL;DR

エラーオブジェクトにリクエスト時の設定が含まれているので、これを axios.request メソッドに渡す事で再実行することが出来ます

import axios from 'axios'
const client = axios.create({ baseURL: 'https://hoge.example/api/v1/' })

client.interceptors.response.use(
  (response) => {
    return Promise.resolve(response)
  },
  (err) => {
    // json文字列になっているままだとエラーになる為
    if (typeof config.data === 'string') {
      config.data = JSON.parse(config.data)
    }

    return axios.request(err.config)
  }
)

リトライの無限ループ対策

configにプロパティを追加して、リトライ回数を見るように実装しました

import axios from 'axios'

const LIMIT_RETRY_COUNT = 2

client.interceptors.response.use(
  (response) => {
    return Promise.resolve(response)
  },
  (err) => {
    if (config.retryCount > LIMIT_RETRY_COUNT) {
      return Promise.reject(err)
    }

    if (Number.isInteger(config.retryCount)) {
      config.retryCount += 1
    } else {
      config.retryCount = 1
    }

    return axios.request(err.config)
  }
)

ただしaxiosのv0.19.0ではこのやり方(custom config)が効かなくなっているので、もしこのバージョンを使用している場合はバージョンを上げる必要があります。
0.18系は問題ありません。

6
4
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
6
4