首页 > 解决方案 > 我如何知道我的 Firestore 交易是否失败?

问题描述

我正在使用此代码更新我的文档。

Future<void> save() async {
  print('league save');
  final DocumentReference ref = 
    Firestore.instance.collection('leagues').document(_documentName);
Firestore.instance.runTransaction((Transaction tx) async {
  DocumentSnapshot postSnapshot = await tx.get(ref);
  if (postSnapshot.exists) {
    await tx.update(ref, _getDocument());
    print('league save complete');
  }
});
}

我相信这有时可能会失败,但我不确定。我得到一个错误。

我怀疑它有时会失败的原因是因为我的侦听器(在应用程序的其他地方)并不总是在文档更改时被解雇。

如何记录或捕获事务中的错误?

标签: google-cloud-firestoreflutter

解决方案


runTransaction 只是一个普通的异步操作,您可以使用 then 和 catchError 跟进:

Firestore.instance.runTransaction((Transaction tx) async {

  // do whatever      

}).then((val) {

 // do something upon success

}).catchError((e) {

 // do something upon error 

});

如果需要,您可以跳过 .then()


推荐阅读