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

Jithesh Kt picture Jithesh Kt · Nov 2, 2017 · Viewed 26k times · Source

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);
}

Answer

chithra picture chithra · Nov 27, 2017

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;
        }
      })