user8955046
user8955046

Reputation: 47

When using axios interceptors I can't get an AxiosError instance inside a try and catch block

When I use axios interceptors to log the user out when the error code is 401 I can't get any error code outside my interceptor. Let's suppose I have a try and catch block outside axios interceptors. So what happens is that I'm not able anymore to get an AxiosError instance in any try and catch block outside axios interceptors. Does anyone knows how to fix this?

Below is my interceptor:

api.interceptors.response.use( (response: AxiosResponse) => response,

(error: AxiosError) => {

if (error.response?.status === 401) signOut();

},

);

Below is a catch and try block example (the result is undefined):

try {

} catch (err) {

console.log(err.response.status);

}

Upvotes: 2

Views: 2525

Answers (2)

m yadav
m yadav

Reputation: 1829

You should do "throw error;" like below.

api.interceptors.response.use(     
(response: AxiosResponse) => response,     
(error: AxiosError) => {       
   if (error.response?.status === 401) {         
     signOut();       
   }       
   console.log('throwing error');       
   throw error;     
},   );

Upvotes: 2

Anees Hikmat Abu Hmiad
Anees Hikmat Abu Hmiad

Reputation: 3560

You need to return the Error too if you override the inspector's error, to allow to try catch detect error...

for example:

return error.response ? error.response : Promise.reject(new Error(error));

Inspectors Response Sample:

// Add interceptors for validate authorization
instance.interceptors.response.use(
  (response) => {
    // do somthing if its needed
    // return response
    return response;
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      // Re-request instance if refresh token updated successfully
      return instance.request(error.config);
    }

    return error.response ? error.response : Promise.reject(new Error(error));
  }
);

Upvotes: 2

Related Questions