0

如果由于 Internet 连接速度慢而导致请求需要很长时间才能解决,Firebase 会发出错误。这是错误:

@firebase/firestore:Firestore (7.9.2):无法访问 Cloud Firestore 后端。连接失败 1 次。最近的错误:FirebaseError: [code=unavailable]: The operation could not be completed 这通常表示您的设备目前没有健康的互联网连接。客户端将在离线模式下运行,直到它能够成功连接到后端。

在尝试捕获此错误时,我遇到了 redux-thunks 的奇怪行为。我的 api 函数能够在其catch()块中捕获 firebase 错误,但未在catch()thunk 操作中的块中捕获。下面是一些伪代码来更好地说明这一点:

api.js

getDoc () {
  return firebase.firestore().doc().get().then(result => {
    return result
  }).catch(error => {
    //error caught here
    console.log(error)
  })
}

thunks.js

action () {
  api.getDoc().then(result => {
    //result contains the error
    dispatch(success(result));
  })
  .catch(error => {
    //not being reached
    dispatch(failed(error))
  })
}

我创建了一个代码沙箱来重现错误。随意玩弄代码。当您在应用程序获取数据时离线时,将引发 firebase 错误,并且控制台将显示后端 api 捕获了错误,但 thunk 操作未能这样做。我不确定这是我的错误还是 redux-thunk 库或 firebase 库的限制。

问题:如何处理此错误,以便我的 thunk 操作不会将错误发送为成功?

任何帮助都将受到热烈欢迎。

4

2 回答 2

2

该消息只是给您的通知。这不是一个真正的错误,你无法捕捉到它。Firestore 不会将网络问题视为错误。它只是在后台不断重试。

于 2020-03-07T00:23:44.510 回答
0

如果有人遇到此错误,这是一个解决方案。

最简单的解决方案是从 api 函数中删除catch()块并在调用者函数中捕获错误。根据问题中提供的示例代码,唯一的修改是对api.js文件:

getDoc () {
  return firebase.firestore().doc().get().then(result => {
    return result
  })
}

在测试时,如果错误被 firebase 抛出,thunk 的catch()块会被击中,从而调度错误动作。

于 2020-03-16T07:29:17.200 回答