Axios Errors Handling

With try-catch

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    // Process successful response data
  } catch (error) {
    if (error.response) {
      // Server responded with a status code outside the range of 2xx
      console.log('Server Error:', error.response.data);
    } else if (error.request) {
      // Request made but no response received, Something went wrong. Please try again later.
      console.log('Request Error:', error.request);
    } else {
      // Something happened while setting up the request , Something went wrong. Please try again later.
      console.log('Error:', error.message);
    }
  }
}
 
===== can be done like this: 
 

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    // Process successful response data
  } catch (error) {
    if (error.response) {
      // Server responded with a status code outside the range of 2xx
      console.log('Server Error:', error.response.data);
  return;
    } 
 
// for other errors 
  console.log('Something went wrong. Please try again later.');
  return;
  }
}

 

 

Without try-catch

 let URL = 'https://jsonplaceholder.typicode.com/usess';
      axios.get(URL) // send a GET request
        .then((response) => {
          console.log("success");
        })
        .catch((error) => { // error is handled in catch block
          if (error.response) { // status code out of the range of 2xx
            console.log("Data :" , error.response.data);
            console.log("Status :" + error.response.status);
          } else if (error.request) { // The request was made but no response was received , Something went wrong. Please try again later.
            console.log(error.request);
          } else {// Error on setting up the request , Something went wrong. Please try again later.
            console.log('Error', error.message);
          }
        });
 
===== can be done like this:
let URL = 'https://jsonplaceholder.typicode.com/usess';
      axios.get(URL) // send a GET request
        .then((response) => {
          console.log("success");
        })
        .catch((error) => { // error is handled in catch block
          if (error.response) { // status code out of the range of 2xx
            console.log("Data :" , error.response.data);
            console.log("Status :" + error.response.status);
return;
          } 
  // for other errors 
   console.log('Something went wrong. Please try again later.');
return;
        });

Leave a Comment

Your email address will not be published. Required fields are marked *