android - React Native App 在网络错误时崩溃
问题描述
我正在开发一个文档上传应用程序,使用本机反应。如果网络良好,文档会上传,但如果网络出现故障,应用程序会突然崩溃。例如 - 如果我在 4G 网络上上传文件,那么我会从 API 获得成功,但如果网络速度突然下降到 2G 网络,即 20KB/S,那么我会收到“网络请求失败/网络错误”并且应用程序崩溃。
我已经使用 catch 块处理了错误,但应用程序仍然崩溃,即使网络不可用或速度下降,我应该怎么做才能避免这种崩溃?
下面是我的代码 -
try{
var form = FormData();
form.append("user_id",this.state.userId);
form.append('file', {
uri: this.state.path,
type: 'image/jpg',
name: 'image.jpg',
});
axios({
method:"POST",
url:"http://xxxxx/xxxx",
timeout:50000,
data:form
})
.then(response => console.log(response))
.catch(error=>console.log(error));
}
catch(error){
console.log(error);
ToastAndroid.show("Internal error, please try again");
}
注意 - 我使用了 react-native-image-picker,因为可以使用相机捕获文档,也可以从设备中存在的现有文件上传文档。
还在清单文件中添加了所有权限以访问 Internet。
请帮忙
解决方案
那是一个例外。我想您需要捕获异常 BadNetwork 或超时您需要捕获它并且应用程序不应该崩溃只需确保在捕获中您需要显示显示无法连接到服务器的对话框。或者您需要检查您是否有网络连接,然后只让用户发送请求显示不可取消的对话框希望有帮助。
推荐阅读
- r - 在具有持续时间条件的时间序列中找到峰值
- debian - 无法初始化 GTK!是否设置了 DISPLAY env var/xhost?在 Debian WSL 上
- node.js - 如何计算使用node js生成的文件的大小?
- amazon-web-services - 在模板中向 AWS lambda 函数添加多个安全组
- ruby-on-rails - 如何在另一个 .html.erb 文件中调用 .html.erb 文件
- python - 如何在 Python 中调整图片大小
- ffmpeg - ffmpeg打不开m3u8链接
- python - 如何以正确的顺序安装多个 .whl 文件
- python-3.x - TypeError: __init__() 接受 1 到 6 个位置参数,但给出了 7 个
- google-sheets - 在谷歌表格中执行单元格功能