首页 > 解决方案 > 如何检查 Axios 调用是否因没有 Internet 连接而失败?

问题描述

我试图找出一种准确的方法来检测由于没有互联网连接而导致的 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});
    }
}

标签: reactjsreact-nativenetworkingserveraxios

解决方案


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

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

推荐阅读