Firestore事务仅静默失败无异常抛出,如何实现事务失败报错?
Firestore 事务并发冲突直接抛出异常解决方案
核心原因
Firestore Python SDK的@firestore.transactional装饰器默认开启了最多5次事务自动重试逻辑:当检测到事务读取的文档在提交前被其他进程修改时,SDK会自动拉取最新的文档快照,重新执行整个事务逻辑,不会直接抛出异常,这就是你测试时看不到错误提示、事务也没有按预期直接失败的原因。
实现方案
要实现并发修改时事务直接失败、抛出明确异常,只需修改事务装饰器配置,关闭自动重试即可:
- 给
@firestore.transactional装饰器传入max_attempts=1参数,禁用自动重试,此时发生并发冲突会直接抛出google.api_core.exceptions.ConcurrentUpdateError异常 - 按需捕获异常做后续处理
调整后代码示例
from google.api_core.exceptions import ConcurrentUpdateError transaction = db.transaction() doc_ref = db.collection('mycollection').document('mydoc') @firestore.transactional(max_attempts=1) def update_in_transaction(transaction, doc_ref): snapshot = doc_ref.get(transaction=transaction) my_value = snapshot.get(u'my_value') transaction.update(doc_ref, { u'my_value': 'someothervalue' }) try: update_in_transaction(transaction, doc_ref) except ConcurrentUpdateError: print("检测到文档被其他进程修改,当前事务已失败") # 如需上层感知错误,直接抛出即可 raise
内容的提问来源于stack exchange,提问作者poiuytrez
相关产品推荐
相关产品推荐

