How can I use a try...catch block to handle Axios errors?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can I use a try...catch block to handle Axios errors?
Asked by:
57 Viewed 57 Answers
Responsive Ad After Question

Answer (57)

Best Answer
(473)
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(); ```