Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle net::ERR_CONNECTION_REFUSED in Axios - Vue.js

Below is my connection request code :

doLogin(this.login).then(response => {
        var token = response.data.token;
        localStorage.setItem('AUTH_TOKEN', JSON.stringify(token));
        this.$router.push({name: 'Devices'});
        });
      }).catch(error => {
        console.log(error.response.data.message);
      });

the catch() part works fine for http errors (like 400, 404, 403..etc). But when my server is offline this script just throws net::ERR_CONNECTION_REFUSED. Is there any way to handle this error and let the front-end user know that the server is currently offline.?

Here is the doLogin() function just in case,

function doLogin(data) {
  const url   = 'http://localhost:3000/authenticate';
  return axios.post(url,data);
}
like image 533
Jithesh Kt Avatar asked Nov 02 '17 05:11

Jithesh Kt


4 Answers

You can try this in the catch part:

catch(error => {
        if (!error.response) {
            // network error
            this.errorStatus = 'Error: Network Error';
        } else {
            this.errorStatus = error.response.data.message;
        }
      })
like image 98
chithra Avatar answered Oct 17 '22 17:10

chithra


You may use interceptors:

axios.interceptors.response.use(
    response => {
        return response
    },
    error => {
        if (!error.response) {
            console.log("Please check your internet connection.");
        }

        return Promise.reject(error)
    }
)
like image 28
Sinan Eldem Avatar answered Oct 17 '22 16:10

Sinan Eldem


You could verify yourself like PanJunjie潘俊杰 suggested, or make use of a library like sindresorhus/is-reachable. The latter would be my preferred option.

Cheers!

like image 2
chrisg86 Avatar answered Oct 17 '22 17:10

chrisg86


You should do the same validation that @chithra pointed out in the .then() because i'm having a weird issue when testing requests with my servers down, the "response" comes as if it was a success.

Also, on the .then() do it with response.status instead of response.error

like image 1
Leo Avatar answered Oct 17 '22 16:10

Leo