Three common ways to handle AxiosError using Axios

Insert image description here Handling when using Axios AxiosError there are several common methods:

  1. Catch Exception: Using try-catch Statement
try {
  const response = await axios.get('/api/data');
  // Process response data
} catch (error) {
  if (error.response) {
    // The request was successful but the status code is not there 2xx scope
    console.log(error.response.data);
    console.log(error.response.status);
    console.log(error.response.headers);
  } else if (error.request) {
    // Request sent but no response received
    console.log(error.request);
  } else {
    // An error occurred while setting up the request
    console.log('Error', error.message);
  }
} 
  1. interceptors Blocker: Using Axios Instance
const instance = axios.create();

instance.interceptors.response.use(
  (response) => {
    // Handle successful response
    return response;
  },
  (error) => {
    // Handling error responses
    if (error.response) {
      // The request was successful but the status code is not there 2xx scope
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // Request sent but no response received
      console.log(error.request);
    } else {
      // An error occurred while setting up the request
      console.log('Error', error.message);
    }
    return Promise.reject(error);
  }
); 
  1. Use axios.isAxiosError() to determine if the error came from Axios:
axios.get('/api/data')
  .then((response) => {
    // Process response data
  })
  .catch((error) => {
    if (axios.isAxiosError(error)) {
      // deal with AxiosError
      if (error.response) {
        // The request was successful but the status code is not there 2xx scope
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
      } else if (error.request) {
        // Request sent but no response received
        console.log(error.request);
      } else {
        // An error occurred while setting up the request
        console.log('Error', error.message);
      }
    } else {
      // Handle other types of errors
      console.log('Error', error);
    }
  }); 

This document is transferred from https://blog.csdn.net/sky6862/article/details/137636514,If there is any infringement,Please contact to delete。