0
0

More than 1 year has passed since last update.

axios(Promise)で通信が成功しているのにcatchに入ってしまう

Last updated at Posted at 2022-09-03

現象

JSでaxiosを使って通信処理を書いたときに、通信が成功しているのにcatchの処理が走っていた。
通信が成功しているのは開発者ツールのネットワークタブで確認済み。
問題のコードは以下。
実際にはいろいろと処理を書いているが、この記事では必要な部分だけを抽出。
API呼び出し時に共通の処理が入るため、_axios.jsにaxiosのインスタンス化と共通処理を書き、
Customer.jsでそれを呼び出し使用。

_axios.js
import axios from "axios";

export const _axios = createAxiosInstance();
function createAxiosInstance(){
  const axiosInstance = axios.create();

  axiosInstance.interceptors.response.use(
    (response) => response,
    (error)=>{
      if (error.response) {
        console.log(error.response.status);
        console.log(error.response.data);
        console.log(error.response.headers);
      } else if (error.request) {
        console.log(error.request);
      } else {
        console.log('Error', error.message);
      }
      console.log(error.config);
      return Promise.reject(error)
    }
  )

  return axiosInstance;
}
Customer.js
// 
// 省略
//
import {_axios} from 'modules/_axios';

// 
// 省略
//

// 顧客一覧取得
function getCustomerList(setCustomerList){
  _axios({
    method: "get",
    url: config.API_GET_CUSTOMER_LIST, //別ファイルで定義された定数
  })
  .then(function (response) {
    setCustomerList(response.data.customer_list);
    return true;
  })
  .catch(function (error) {
    console.log("顧客一覧取得失敗");
  })
  .finally(function () {
  });
}

通信はちゃんと200で返ってきているのに「顧客一覧取得失敗」が出力されてしまう。

原因

ここで、そういえばcatchの中でエラー内容を出していないことに気づく。
とりあえずエラーを出してみる。
↓↓ Customer.js

// 
// 省略
//
import {createAxiosInstance} from 'modules/_axios';

// 
// 省略
//

// 顧客一覧取得
function getCustomerList(setCustomerList){
  axiosCustomerManagement({
    method: "get",
    url: config.API_GET_CUSTOMER_LIST, //別ファイルで定義された定数
  })
  .then(function (response) {
    setCustomerList(response.data.customer_list);
    return true;
  })
  .catch(function (error) {
+   console.log(error);
    console.log("顧客一覧取得失敗");
  })
  .finally(function () {
  });
}

実行・・・

コンソール
TypeError: setCustomerList is not a function
    at Customer.js:93:5

thenの中で実行している「setCustomerList」という関数が定義されていないだけでした。。。

まとめ

Promiseのthenの中でエラーが起きた場合にはcatchに入る。
いろいろと原因を想像する前に、まずはコンソールで出力して全情報をかき集める。
今回 ↑ これをしなかったのが原因。

0
0
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
0
0