Axios is one of the most popular libraries when it comes to the making of HTTP requests. It’s a great library, but it’s not perfect. In this blog, we take a look at some of the errors that can occur when using this library and how to deal with them.
How To Deal With Errors In Axios?
A common solution to deal with errors in Axios is to capture errors in the catch() block, as seen below. Intercepting requests or answers before their being treated by then or catch.
Option 1
A common way is to capture errors in the catch() block, as seen below:
axios.get('/api/xyz/abcd') .catch(function (error) { if (error.response) { // Request made and server responded console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } });
Option 2
Intercepting requests or answers prior to their being treated by then or catch
axios.interceptors.request.use(function (config) { // Do something before request is sent return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Do something with response data return response; }, function (error) { // Do something with response error return Promise.reject(error); });
Option 3
If you would like to acquire access to the entire error body, follow the steps below:
async function login(reqBody) { try { let res = await Axios({ method: 'post', url: 'https://myApi.com/path/to/endpoint', data: reqBody }); let data = res.data; return data; } catch (error) { console.log(error.response); // this is the main part. Use the response property from the error object return error.response; } }
Option 4
You may use the following syntax: error.response.data. For exampple, the backend returned an error property. As a result, you should use error.response.data.error. The code is:
axios .get(`${API_BASE_URL}/students`) .then(response => { return response.data }) .then(data => { console.log(data) }) .catch(error => { console.log(error.response.data.error) })
Conclusion
We hope you enjoyed our article about dealing with errors in Axios. We are confident that with this information, you will be able to make the most of your Axios development experience.
If you still have any further concerns or problems, please feel free to leave us a comment. Thank you for reading; please make sure to share this helpful article with others!