Skip to content
Advertisement

catch and handle connection refused error using Axios

I use Axios for my VueJs app and have a Express REST Api. When my VueJs app is not able to call the backend (connection refused / the node server is not running)

How can I catch this error? I tried to log the error using an interceptor

  instance.interceptors.response.use(res => res, (err) => {
    console.log({ err });

    if (err.response.status === 401) {
      // unauthorized
    }

    return err;
  });

but when logging the err I only get

Error: Network Error

with response: undefined

Should I sign out the user because there is nothing he can do then or should I just show an error alert and let him stay?

Advertisement

Answer

try this

axios.interceptors.response.use(
  function(response) {
  return response;
 },
 function(err) {
   if (err.response.status === 401) {
     // unauthorized
   }

    return Promise.reject(err);
  }
);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement