I use the axios interceptors to handle some errors, specially the errors without response. And in some parts of my project, I use the message contained in the error.response.data for validations and showing a messaged stored in the backend. But this interceptor is not preventing me from having to check if the error has a response.
My interceptor:
axios.interceptors.response.use(
function (response) {
...
},
function (error) {
if (!error.response) {
...
return Promise.reject(new Error(error.message))
}
An example of a request that depends on having the error.response:
this.$store.dispatch('updateField', { [this.fieldKey]: this.value ? this.value : null }).catch((error) => {
this.validateField(error.response.data)
})
But I'd have to put the validateField call inside an if(eror.response) to avoid an error in the console, and spread this if all over my code?
response can be treated as optional, because it actually is:
this.validateField(error.response?.data)
Or normalized error that contains needed properties and doesn't rely on the structure of Axios error can be created in an interceptor:
function (rawError) {
const error = new Error(error.response?.data?.myError || error.message);
error.data = error.response?.data || null;
error.headers = error.response?.headers || null;
error.status = error.response?.status || 0;
return Promise.reject(error);
}