Handling Errors

Axios provides detailed error information, including response status codes, which helps in error handling:

axios.get('https://jsonplaceholder.typicode.com/invalid-url')
  .then(response => {
    console.log('Data:', response.data);
  })
  .catch(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.error('Response Error:', error.response.status);
      console.error('Response Data:', error.response.data);
    } else if (error.request) {
      // The request was made but no response was received
      console.error('Request Error:', error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.error('Error Message:', error.message);
    }
  });

Comments

Leave a Reply

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