简体   繁体   English

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

[英]how to catch ethereum contract exception?

This is my simple contract 这是我简单的合同

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];
       }
}

When i am transferring tokens more than intial supply to another account the function transfer should throws exception. 当我向其他帐户转让的代币数量超过初始供应量时,功能transfer应该引发异常。

How can i handle this exception and get to know transaction cannot complete.I am using web3j and calling function transfer like 我如何处理此异常并了解交易无法完成。我正在使用web3j并调用函数传递,例如

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

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

I have never used web3js but you can try using try-catch: 我从未使用过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
}

How can i handle this exception and get to know transaction cannot complete 我该如何处理该异常并了解交易无法完成

There is a single exception (a throw without arguments) in Solidity, which is "out of gas". Solidity中只有一个例外(不带参数的throw ),这是“精疲力尽”。 So your "faulty" transaction is completed, however it ran out of gas. 这样您的“错误”交易完成了,但是用光了。 If you know the transaction hash, you can check gasLimit and gasUsed . 如果您知道交易哈希,则可以检查gasLimitgasUsed If they are equal, your transaction has probably * ran out of gas. 如果他们是平等的,您的交易可能已经*跑出来的气体。 See more information here . 在此处查看更多信息。

* given that you supply more than enough gas that a "correct" transaction requires. *鉴于您提供的天然气超过了“正确”交易所需的数量。

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

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