34

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

5 Answers 5

52

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;
        }
      })
3
  • 23
    This do not allows to distinguish errors like net::ERR_CONNECTION_RESET and net::ERR_CONNECTION_REFUSED and, possibly, other error states. Commented Nov 28, 2018 at 8:27
  • I'm working on vue js application which consumes api and I'm facing similar problem and this works fine for me but the problem is I need to place this in every request which sends to backend api. But what's the best way of approach to handle this by placing at one place?
    – Ruby4Rails
    Commented May 8, 2020 at 18:50
  • 1
    @Ruby4Rails - build a service class for your api with a method for each type, i.e. get(), post(), delete() or whatever. Then you can always handle these edge cases no matter where you call the methods in your api Commented Apr 22, 2021 at 13:06
21

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)
    }
)
1
  • 3
    Great. I just put this in my useEffect() in my NextJS (React) _app.js and display globally a Snackbar from Material-UI from anywhere with React's Global Context.
    – KeitelDOG
    Commented Feb 22, 2021 at 20:59
1

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

0

You can use interceptors

Axios Interceptors

yourAxiosInstance.interceptors.response.use(
  response => response,
  error => {
      if (error.code === 'ERR_NETWORK') {
          alert("No connection");
      }


      return Promise.reject(error)
  }
)
-4

By using npm; a standard package manager for the JavaScript runtime environment Node.js.

With npm:

npm i axios

Next, you should import Axios in your src/App.vue file

import axios from 'axios';

you will need to call it on a lifecycle hook. Here we will use the beforeCreated() lifecycle hook, this is because we will be able to retrieve sensitive data and events that are active with the beforeCreated hook.

 data() {
return {
  network: false,
}; },
beforeCreate() {
axios
  .get("http://localhost:13172/api/product/getproducts")
  .then((response) => {
    console.log(response);
    this.network = true;
  })
  .catch((error) => {
    console.log(error), (this.network = false);
  }); }
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.