【问题标题】:How to 'catch errors in web3.py'如何“捕捉 web3.py 中的错误”
【发布时间】:2019-12-18 02:17:43
【问题描述】:

我试图在交易恢复时捕获 require() 错误,但我得到了交易的哈希值,我正在使用 web3.py

def addParticipants(request):
    web3 = Web3(HTTPProvider(settings.Blockchain_IP_address, request_kwargs={'timeout': 60}))
    project_address = '0x93aeD90401a182247EE28848229531bC78053cd6'
    project = web3.eth.contract(address=project_address,
                                abi=Project_sol.abi,
                                bytecode=Project_sol.bytecode)
    func_to_call = 'addParticipant'
    addParticipant = project.functions[func_to_call]
    result = addParticipant(settings.ADMIN_ACCOUNT,0).transact(  {'from': settings.ADMIN_ACCOUNT, 'gasLimit': '6000000', 'gasPrice': '0', 'gas': 600000})
    web3.eth.waitForTransactionReceipt(result)
    print(result)

实心法:

  function addParticipant(address _Participant, uint _weight)public isOwner returns (bool) {
    require(_weight!=0,"weight cannot be null");
    require(status,"this Donation is closed");

    Participants[_Participant].weight = _weight;
    Participants[_Participant].status = true;
    ParticipantsIndex[ParticipantsIndexSize] = _Participant;
    ParticipantsIndexSize++;

    emit ParticipantAction(_Participant, 'added');
    return true;
  }

函数应该抛出错误说“权重不能为空”

【问题讨论】:

  • 您能否指向 web3.py 文档,该文档表明它的行为预期与您所描述的一样?
  • @EdNoepel ,在文档中没有关于错误的示例,但我有使用 web3.php 的经验,我得到了预期的结果。

标签: python blockchain ethereum web3


【解决方案1】:
from web3 import exceptions

try:
    result = addParticipant(......)
    web3.eth.waitForTransactionReceipt(result)
    print(result)
except exceptions.SolidityError as error:
    print(error)

【讨论】:

  • 请解释这是如何回答问题的(仅代码的答案不是很好)...
  • 您好,还原的事务会抛出 SolidityError,您可以使用异常处理 w3schools.com/python/python_try_except.asp 捕获它并根据需要处理错误。在上面的代码中,错误只是被打印出来了。
猜你喜欢
  • 2021-12-02
  • 2020-03-18
  • 1970-01-01
  • 2010-12-06
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 2010-12-05
相关资源
最近更新 更多