How do I handle my errors using Axios?
Axios interceptor:
Axios interceptors are functions that Axios calls for every request. You can use interceptors to transform the request before Axios sends it, or transform the response before Axios returns the response to your code.
For JavaScript
For TypeScript
Most people will be handling the errors in each and every request. For example:
const { error } = await axios.get("user");
if(error) {
alert(error);
} else {
// Something happens here if no error occurs
}
The above method also works, but we have to write code for each and every request, which is kind of annoying. Axios interceptor makes it easier.
You can do the same for every successful request, in case you want to show a success toast. For example:
// See line number 11 in the above screenshots(response) => {
// Only when there is a message object from the backend
if(response.data?.message) {
alert(response.data.message); // For example: Login ssuccessful
}
return response.data;
}
Read more about Axios Interceptor here.
Axios Interceptor code example (JavaScript): axios.js
Axios Interceptor code example (TypeScript): axios.ts