没有互联网时如何在firestore中捕获错误

时间:2018-05-26 13:30:09

标签: javascript firebase google-cloud-firestore react-native-firebase

我最近将我的应用程序从firebase更新到了firestore,但仍处于脱机状态。我使用react-native-firebase来集成firestore并禁用它的perisistance但是在没有互联网时仍然没有得到任何catch错误。 这是我删除数据的代码,但是当没有互联网不能解决承诺时,捕获永远不会出错。

firebase.firestore().collection('d').doc(deviceid).delete().then(function () {
                                    console.log("Device Deleted");
                                    that.setState({
                                        loading: false
                                    });
                                    Toast.show('Device Deleted Succesfully', {
                                        duration: Toast.durations.SHORT,
                                        position: Toast.positions.TOP,
                                        shadow: true,
                                        animation: true,
                                        hideOnPress: true,
                                        delay: 0,
                                    });

                                }).catch(function (err) {
                                    console.log(err);
                                    that.setState({
                                        loading: false
                                    });
                                })

3 个答案:

答案 0 :(得分:3)

当没有网络连接时,Firestore和实时数据库SDK不会抛出错误。他们将默默地重试连接,希望设备很快重新获得网络连接。之所以这样,是因为大多数开发人员都不希望他们的应用因为用户进入隧道而退出,或者以强制网络重置的方式在移动塔之间切换,因此不会出现问题。

为了有效地利用在线数据库,设备应该在大多数时间处于在线状态,这就是SDK正在优化的情况。

答案 1 :(得分:0)

创建自己的帮助函数进行删除,如果没有Internet连接则抛出错误。您可以通过不调用.collection()而不是将完整路径d + deviceid传递给它来使API更清晰。

function onlineOnlyDelete(path) {
  if(!deviceApi.hasInternet()) throw 'No Internet, no delete'
  return firebase.firestore().doc(path).delete()
}

firebase.firestore().collection('d').doc(deviceid)替换为onlineOnlyDelete(d+deviceid),你应该好好去

答案 2 :(得分:0)

参考此thread。我设置了以下检查:

.then(() => {
  if (snapshot.empty && snapshot.metadata.fromCache) {
     throw new Error('Failed to fetch ideas');
  }
})

然后稍后我发现了错误,并将应用程序状态设置为包括错误以及该批处理特定的参数,例如startIndexstopIndex,这些在以后将很重要。渲染文档时,为BatchError保留了一种情况,正如我所说的那样,在这种情况下,用户将看到带有附加了回调的Refetch按钮。使用批处理元数据,回调函数可以重新初始化特定的批处理请求。