如何在web3.py中正确捕获wait_for_transaction_receipt的TimeExhausted异常?
解决web3.py中wait_for_transaction_receipt()的TimeExhausted异常捕获失败问题
问题根源
报错AttributeError: type object 'Web3' has no attribute 'TimeExhausted'的核心原因是:你错误地尝试从Web3类中访问TimeExhausted异常,实际上这个异常属于web3.exceptions模块,并非Web3类的属性。
修正后的代码
先导入正确的异常类,再调整捕获逻辑:
from web3 import Web3 from web3.exceptions import TimeExhausted # 新增该异常的导入语句 while True: try: tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash, timeout=45) print(f"{str(dt.utcnow())[:-7]} | Transaction receipt: {tx_receipt}") break except TimeExhausted as e: print(f"{str(dt.utcnow())[:-7]} | A Inner exception caught: {e}.") print( f"{str(dt.utcnow())[:-7]} | Timed out waiting for transaction. " + f"Will update SMA & wait again..." ) update_sma_data()
说明
从报错栈的信息可以明确看到,触发的异常是web3.exceptions.TimeExhausted,因此必须直接捕获这个类,而非通过Web3.TimeExhausted的方式访问。修正后,超时触发异常时会被正常捕获,执行update_sma_data()后会继续循环等待交易上链,直到成功获取回执后退出循环。
内容的提问来源于stack exchange,提问作者flim.eth
相关产品推荐
相关产品推荐

