繁体   English   中英

如何捕捉以太坊合约异常?

[英]how to catch ethereum contract exception?

这是我简单的合同

contract Test {
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function Test(
        uint256 initialSupply
        ) {
        balanceOf[msg.sender] = initialSupply;              // Give the creator all initial tokens
    }

    /* Send coins */
    function transfer(address _to, uint256 _value) {
        if (balanceOf[msg.sender] < _value) throw;           // Check if the sender has enough
        if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
        balanceOf[msg.sender] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
    }

function gettokenBalance(address to)constant returns (uint256){
          return balanceOf[to];
       }
}

当我向其他帐户转让的代币数量超过初始供应量时,功能transfer应该引发异常。

我如何处理此异常并了解交易无法完成。我正在使用web3j并调用函数传递,例如

Test test = Test.load(contractObj.getContractAddress(), web3j, credentials, gasprice,gaslimit);

TransactionReceipt balanceOf = test.transfer(new Address(address), transferBalance).get(); 

我从未使用过web3js,但是您可以尝试使用try-catch:

try{
  Test test = Test.load(contractObj.getContractAddress(), web3j, credentials, gasprice,gaslimit);

  TransactionReceipt balanceOf = test.transfer(new Address(address), transferBalance).get(); 
} catch (Exception e){
  // log you exception
}

我该如何处理该异常并了解交易无法完成

Solidity中只有一个例外(不带参数的throw ),这是“精疲力尽”。 这样您的“错误”交易完成了,但是用光了。 如果您知道交易哈希,则可以检查gasLimitgasUsed 如果他们是平等的,您的交易可能已经*跑出来的气体。 在此处查看更多信息。

*鉴于您提供的天然气超过了“正确”交易所需的数量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM