I’m trying to produce an error in transaction and my question is when does transaction produces error ? I tried inserting random non existent collection and document, go offline, still it doesn’t catch any error.
In what conditions does transaction error out ?
var db = Firestore.firestore()
let ref = db.collection("foo").document("bar")
db.runTransaction({ transaction, errorPointer -> Any? in
var document: DocumentSnapshot
do {
try document = transaction.getDocument(ref)
} catch let fetchError as NSError {
// no Error here even if ref doesn't exist or I go offline
errorPointer?.pointee = fetchError
return nil
}
return nil
}) { _, error in
if let error = error {
print("Transcation Completion Error: (error)")
} else {
print("Transaction Succeeded!")
}
}
2
Answers
If you just want to test error handling then just throw your own error from within the transaction. The transaction closure has two arguments, the transaction object and an error pointer. Assign the error pointer an
NSError
and handle it in the completion block.Beyond this, a transaction could fail for a number of reasons, such as performing a read operation after a write operation, a network error, exceeding the allotted data-usage limit, or too many failed attempts at retrying the transaction (because the underlying documents were modified outside the transaction). Further reading at link below.
https://firebase.google.com/docs/firestore/manage-data/transactions#transaction_failure
According to Firebase documentation, a transaction can fail following the next options:
Before any write operations, read operations must always occur first.
In this instance, the transaction is restarted automatically. A
certain number of times the transaction is retried.
and index items that it modifies. This contains the size of the
target document and the sizes of the index items eliminated due to
the operation.
When a transaction fails, it generates an error and does not write any data to the database. You don’t have to roll back the transaction because Cloud Firestore does it for you.
Also, I would like to suggest you to check the NSError for Swift, here is a Github Repository that provides information of NSError, as well as this documentation that also describes the NSError of how to handle failed transactions and give appropriate error messages to the user as a feedback.