Firebase spits out an error if a request takes too long to resolve due to slow internet connections. Here is the error:
@firebase/firestore: Firestore (7.9.2): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=unavailable]: The operation could not be completed This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
I ran into an odd behaviour with redux-thunks when trying to catch this error. My api function was able to catch the firebase error in its catch()
block but was not caught in the catch()
block within the thunk action. Here is some pseudocode to illustrate this better:
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))
})
}
I created a code sandbox to reproduce the error. Feel free to play around with the code. When you go offline while the app is fetching data, the firebase error will get thrown, and the console will show that the backend api caught the error but the thunk action failed to do so. I am not certain if this is an error on my part or a limitation of the redux-thunk library or firebase library.
Question: How can I handle this error so my thunk action does not dispatch an error as a success?
Any help will be warmly welcomed.
Here is a solution in the event anyone comes across this error.
The simplest solution is to remove the catch()
block from the api function and catch errors at the caller function. Based on the example code provided in the question, the only modification would be to the api.js file:
getDoc () {
return firebase.firestore().doc().get().then(result => {
return result
})
}
While testing, if the error gets thrown by firebase, the thunk's catch()
block is hit which dispatches the error action.