22.Error
An error will undo all changes made to the state during a transaction.
You can throw an error by calling require
, revert
or assert
.
require
is used to validate inputs and conditions before execution.revert
is similar torequire
. See the code below for details.assert
is used to check for code that should never be false. Failing assertion probably means that there is a bug.
Use custom error to save gas.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
contract ErrorIntro {
function testRequire(uint256 _i) public pure {
// “Require” 应该用于验证以下条件:
// 输入
// 执行前的条件
// 对其他函数调用的返回值
require(_i > 10, "Input must be greater than 10");
}
function testRevert(uint256 _i) public pure {
// 当需要检查的条件比较复杂时,Revert是非常有用的。 这段代码与上面的示例执行的是完全相同的操作。
if (_i <= 10) {
revert("Input must be greater than 10");
}
}
uint256 public num;
function testAssert() public view {
// Assert应该仅用于测试内部错误和检查不变量。
assert(num == 0);
}
// 自定义error
error MyError(address caller, uint256 i);
function testCustomError(uint256 _i) public view {
if (_i > 10) {
revert MyError(msg.sender, _i);
}
}
}