'How to Check if Axios Call Fails due to No Internet Connection?

I'm trying to figure out an accurate way to detect axios call failure due to no internet connection.

Does axios call failure return a specific response object or specific response status code or throw a specific error details for the no internet connection scenario?

Example of what i will use the "detection of axios failure due to no internet connection" for

try {
    const res = await server.get('/auth/user?', {
            params: {
                refreshToken: refreshToken,            
                userID: userID
            }
        }
    );

    if(res.user.data){
        dispatch({type: LOGIN_USER_SUCCESS, payload: res.data.user});
    } else {
        if(res.axiosFailsDueToNoInternetConnection){
            alert('no internet connection');
            dispatch({type: RELOAD});
        }
    }

} catch (error) {
    if(error.dueToNoInternetConnection){
        alert('no internet connection');
        dispatch({type: RELOAD});
    }
}


Solution 1:[1]

In your catch clause you can check whether the error is caused by network error or not:

catch (error) {
    if(error.toJSON().message === 'Network Error'){
        alert('no internet connection');
        dispatch({type: RELOAD});
    }
}

Solution 2:[2]

The marked answer is not correct, because a "Network Error" error could also happen in case of a withCredintials pilot request failure.

And you must differentiate between a server error and a client-side error by checking whether the error.response property object exists or not.

catch (error) {
    if(!window.navigator.onLine && !error.response && error.code === "ERR_NETWORK"){
alert('no internet connection');
    }
}

I must also mention that the checking for window.navigator.onLine should be done inside the try block before sending and awaiting a request and not in the catch block. However, it must be almost correct either ways

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Al Ped
Solution 2