Custom errors
Custom errors are a cheaper and clearer alternative to long revert strings. You declare them once and revert with them, optionally passing values that explain what went wrong.
A revert string is stored in the contract's bytecode, which makes the contract bigger and the failure more expensive. A custom error is encoded as just a four-byte selector plus its arguments.
Callers can catch custom errors by name. Tools like Foundry and ethers.js decode them using the ABI, so the user sees NotEnough(5, 10) instead of a blank failure.
Use require for simple checks with a short message, and custom errors inside if statements when you want to save gas or return details. Pick one style per project and use it consistently.
Errors can be defined outside any contract, so several contracts in a file can share them. Give each error a specific name such as Unauthorized or DeadlinePassed rather than a generic one.
error Unauthorized(address caller); contract Vault { error NotEnough(uint256 have, uint256 need); error DeadlinePassed(uint256 deadline); address public owner = msg.sender; uint256 public deadline = block.timestamp + 7 days; mapping(address => uint256) public bal; function deposit() external payable { if (block.timestamp > deadline) revert DeadlinePassed(deadline); bal[msg.sender] += msg.value; } function take(uint256 amt) external { if (bal[msg.sender] < amt) revert NotEnough(bal[msg.sender], amt); bal[msg.sender] -= amt; (bool ok, ) = msg.sender.call{value: amt}(""); require(ok, "Transfer failed"); } function close() external { if (msg.sender != owner) revert Unauthorized(msg.sender); deadline = block.timestamp; } }
Try it yourself
Add a custom error ZeroAmount() and revert with it in deposit when msg.value is 0. Then compile.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.