14.报错控制
智能合约有三种常用报错方法
require,revert,assert
这三种都有gas refund(gas退还), state updates are reverted(状态回滚)的特性。
此外还有8.0新增的custom error(节约gas)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;
contract Errors{
function testRequire(uint _i) public pure{
require(_i<=10,"error: i>10");
// code
}
function testRevert(uint _i) public pure {
if(_i>10){
revert("error: i>10");
}
//code
}
uint public num=123;
function testAssert()public view {
assert(num==123);
}
function foo()public {
num+=1;
}
}
custom error节约gas
require如果报错信息是很长的字符串,会浪费gas
error MyError(address caller,uint i);
function testCustomError(uint _i)public view {
if(_i>10){
revert MyError(msg.sender,_i);
}
}
}