32

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);
}
haMzox
  • 2,073
  • 1
  • 12
  • 25
Jithesh Kt
  • 2,023
  • 6
  • 32
  • 48

4 Answers4

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;
        }
      })
chithra
  • 756
  • 7
  • 12
  • 21
    This do not allows to distinguish errors like `net::ERR_CONNECTION_RESET` and `net::ERR_CONNECTION_REFUSED` and, possibly, other error states. – Yuriy Petrovskiy Nov 28 '18 at 08: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 May 08 '20 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 – fullStackChris Apr 22 '21 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)
    }
)
Sinan Eldem
  • 5,564
  • 3
  • 36
  • 37
  • 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 Feb 22 '21 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

Leo
  • 472
  • 5
  • 9
-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);
  }); }