reactjs - 如何检查 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});
}
}
解决方案
在您的 catch 子句中,您可以检查错误是否是由网络错误引起的:
catch (error) {
if(error.toJSON().message === 'Network Error'){
alert('no internet connection');
dispatch({type: RELOAD});
}
}
推荐阅读
- video - FFmpeg 无法将 MOD 转换为 MP4
- javascript - 如何在javascript中打印json的标题?
- reactjs - 你可能需要一个合适的加载器来处理这个文件类型——React
- javascript - 如何将服务器响应分配给对象
- prolog - 概率编程:具体化分布和东西?
- python-3.x - 如何使用 python3 在 TinyDB 中创建嵌套值?
- r - 为什么 R glmnet predict 给出一个矩阵而不是一列?
- excel - 从 Excel 粘贴后退出 Word 表
- java - 按字母顺序重新排列字符串中的单词
- mysql - mysql表与主键和外键的关系