12-Solidity8.0-报错控制

410 阅读1分钟

require, revert, assert 这三种方法都具有gas费归还,和状态回滚的这些特性;

require, revert相反;

assert 类型断言

image.png

pragma solidity ^0.8.7;

//require, revert, assert
// - gas refund, state updates are reverted
// custom error - save gas

contract Error{
    function testRequire(uint _i)public pure {
        require (_i <= 10,"i>10");
        //code
    }
     function testRevert(uint _i)public pure {
         if(_i > 10){
             revert ("i > 10");
         }
    }

    uint public num =123;
    function testAssert() public view {
        assert (num == 123);
    }

    function foo() public {
        //调用会使assert 类型断言报错
        num += 1;
    }
    error MyError (address caller, uint i);

    function testCustomError(uint _i) public view {
        if ( _i > 10) {
            revert MyError(msg.sender, _i);
        }
    }
}

最后的错误处理同最开始的 01-Solidity8.0新特性 一样