Error Handling

Always handle errors in your Axios requests to ensure your application can gracefully handle network issues or server errors.

axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
console.log('Data:', response.data);
}) .catch(error => {
if (error.response) {
  // Server responded with a status other than 2xx
  console.error('Response Error:', error.response.status);
  console.error('Response Data:', error.response.data);
} else if (error.request) {
  // Request was made but no response received
  console.error('Request Error:', error.request);
} else {
  // Error setting up the request
  console.error('Error Message:', error.message);
}
});

Comments

Leave a Reply

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