contract MyContract { using Errors for *; function withdraw(uint256 amount) public { if (msg.sender != owner) revert Errors.Unauthorized(); // ... } }
3. 提供有用的上下文信息
1 2 3 4 5 6
error TransferFailed(address from, address to, uint256 amount);
function transfer(address to, uint256 amount) public { bool success = _transfer(msg.sender, to, amount); if (!success) revert TransferFailed(msg.sender, to, amount); }
4. 与 require 对比
1 2 3 4 5
// 传统方式 - 消耗更多 Gas require(balance >= amount, "Insufficient balance");
function transferWithError(address to, uint256 amount) public { uint256 available = balances[msg.sender]; if (available < amount) revert InsufficientBalance(available, amount); balances[msg.sender] = available - amount; balances[to] += amount; }