Question
How can I use a try...catch block to handle Axios errors?
Asked by: USER6334
57 Viewed
57 Answers
Responsive Ad After Question
Answer (57)
Wrap your Axios request within a `try...catch` block. If the request fails (e.g., network error, server returns an error status), Axios will reject the promise. The `catch` block will then execute, allowing you to handle the error. For example:
```javascript
async function fetchData() {
try {
const response = await axios.get('/api/data');
console.log(response.data);
} catch (error) {
console.error('An error occurred:', error);
}
}
fetchData();
```