How to handle errors in Axios
Are you are learning about “How to handle errors in Axios“? In today’s article, I will provide solutions for you to solve the issues. Please follow the below steps to get the problem resolved now
How to deal with errors in Axios
To handle Axios errors, a conventional approach is to catch errors within the catch()
block. Intercepting requests and responses before they are dealt with by then or catch.
Axios handling errors
Solution 1
One way to catch errors in catch()
is to use the following:
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);
}
});
Solution 2
Intercepting requests and responses before they are processed 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);
});
Solution 3
If you want to gain access to the whole error body, do it as shown 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;
}
}
Solution 4
It’s possible to go as follows: error.response.data In my case, the backend gave me a error property. So I used error.response.data.error. My code:
axios
.get(`${API_BASE_URL}/students`)
.then(response => {
return response.data
})
.then(data => {
console.log(data)
})
.catch(error => {
console.log(error.response.data.error)
})
Final Words
The above are useful solutions for the question “How to handle errors in Axios?”, if you can’t solve it well. Please leave a message.