【问题标题】:How to Check if Axios Call Fails due to No Internet Connection?如何检查Axios调用是否因没有Internet连接而失败?
【发布时间】:2020-05-28 09:44:32
【问题描述】:

我正在尝试找出一种准确的方法来检测由于没有互联网连接而导致的 axios 调用失败。

axios调用失败是返回具体的响应对象还是具体的响应状态码或者是无网情况下抛出具体的错误详情?

我将使用“由于没有互联网连接而检测 axios 故障”的示例

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

【问题讨论】:

    标签: reactjs react-native networking server axios


    【解决方案1】:

    在你的catch子句中,你可以检查错误是否是由网络错误引起的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-10
      • 2011-12-02
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多