Axios のエラー処理 質問する

Axios のエラー処理 質問する

私は Axios を使って JavaScript の Promise をよりよく理解しようとしています。私が目指しているのは、Request.js 内のすべてのエラーを処理し、 を使用せずにどこからでも request 関数を呼び出すことですcatch()

この例では、リクエストに対する応答は JSON 形式のエラー メッセージを含む 400 になります。

次のようなエラーが発生しています:

Uncaught (in promise) Error: Request failed with status code 400

私が見つけた唯一の解決策は.catch(() => {})Somewhere.js を追加することですが、それを実行しなくて済むようにしたいと思っています。それは可能ですか?

コードは次のとおりです:

リクエスト

export function request(method, uri, body, headers) {
  let config = {
    method: method.toLowerCase(),
    url: uri,
    baseURL: API_URL,
    headers: { 'Authorization': 'Bearer ' + getToken() },
    validateStatus: function (status) {
      return status >= 200 && status < 400
    }
  }

  ...

  return axios(config).then(
    function (response) {
      return response.data
    }
  ).catch(
    function (error) {
      console.log('Show error notification!')
      return Promise.reject(error)
    }
  )
}

どこか.js

export default class Somewhere extends React.Component {

  ...

  callSomeRequest() {
    request('DELETE', '/some/request').then(
      () => {
        console.log('Request successful!')
      }
    )
  }

  ...

}

ベストアンサー1

リクエストモジュールですべての基本的なエラーを処理したい場合、catch各呼び出しでを使用する必要がない場合は、Axiosのアプローチでは、迎撃機回答について:

axios.interceptors.response.use(function (response) {
    // Optional: Do something with response data
    return response;
  }, function (error) {
    // Do whatever you want with the response error here:

    // But, be SURE to return the rejected promise, so the caller still has 
    // the option of additional specialized handling at the call-site:
    return Promise.reject(error);
  });

axios インターセプターからエラーを返す場合は、catch()以下のようにブロックを介して従来のアプローチを使用することもできます。

axios.get('/api/xyz/abcd')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser 
      // and an instance of http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
   
  });

おすすめ記事