首页 > 解决方案 > 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。

请帮忙

标签: androidreact-native

解决方案


那是一个例外。我想您需要捕获异常 BadNetwork 或超时您需要捕获它并且应用程序不应该崩溃只需确保在捕获中您需要显示显示无法连接到服务器的对话框。或者您需要检查您是否有网络连接,然后只让用户发送请求显示不可取消的对话框希望有帮助。


推荐阅读