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);
}
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;
}
})
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)
}
)
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With