我想知道和
有什么不同contract TestToken {
mapping(address => uint) balance;
error InsufficientBalance(uint256 available, uint256 required);
function transfer(address to, uint256 amount) public {
if (amount > balance[msg.sender])
// Error call using named parameters. Equivalent to
// revert InsufficientBalance(balance[msg.sender], amount);
revert InsufficientBalance({
available: balance[msg.sender],
required: amount
});
balance[msg.sender] -= amount;
balance[to] += amount;
}
// ...
}
和
contract TestToken {
mapping(address => uint) balance;
error InsufficientBalance(uint256 available, uint256 required);
function transfer(address to, uint256 amount) public {
require(balance[msg.sender]<amount, "Insufficient Balance");
balance[msg.sender] -= amount;
balance[to] += amount;
}
// ...
}
处理固体错误
从低级的角度来看,这两种方法是相同的。两者都抛出一个以字节数组作为异常数据的异常。
您可以在低级catch (bytes memory)
块中catch
两个错误
function foo() public {
try this.transfer(address(0x123), 2) {
// ok
} catch (bytes memory data) {
// returns either the encoded object or the encoded string
}
}
但是您只能用"正则"来catch
字符串编码的错误。catch Error(string memory)
块
function foo() public {
try this.transfer(address(0x123), 2) {
// ok
} catch Error (string memory reason) {
// returns the string message
// fails to catch if an object is returned
}
}
文档:https://docs.soliditylang.org/en/v0.8.13/control-structures.html try - catch
注意,在第二个代码片段中有一个逻辑错误。
// `balance` needs to be lower than `amount`
// otherwise fail
require(balance[msg.sender]<amount, "Insufficient Balance");
应该
// `balance` needs to be larger or equal than `amount`
// otherwise fail
require(balance[msg.sender] => amount, "Insufficient Balance");
在require中指定一个条件,如果为false,则返回。
Revert and error是需求的更复杂的版本,您可以在其中指定依赖于上下文的条件并创建自定义错误。
例如
error InvalidAmount (uint256 sent, uint256 minRequired);
contract TestToken {
mapping(address => uint) balances;
uint minRequired;
constructor (uint256 _minRequired) {
minRequired = _minRequired;
}
function list() public payable {
uint256 amount = msg.value;
if (amount < minRequired) {
revert InvalidAmount({
sent: amount,
minRequired: minRequired
});
}
balances[msg.sender] += amount;
}
}
在这段代码中有一个错误叫做"Invalid amount"是必需的,并且依赖于提供给构造函数的最小量。如果金额小于最小金额,事务将返回自定义错误,该错误将指定用户输入的金额和输入构造函数的最小金额。