TExcelTAD
Home › Solidity › Custom Errors

Custom Errors

Since Solidity 0.8.4 you can declare custom errors: named error types with parameters. They are cheaper than string messages and far more informative, because they can carry the actual values that caused the failure.

solidity
error InsufficientBalance(uint256 available, uint256 required);

function withdraw(uint256 amount) external {
    if (amount > balance[msg.sender]) {
        revert InsufficientBalance(balance[msg.sender], amount);
    }
    …
}

Why they are better

require(cond, "string") revert CustomError(args)
Deployment cost each message string stored in bytecode only a 4-byte selector
Runtime cost encodes the whole string encodes 4 bytes + arguments
Data for the caller a sentence a typed error with values
Front-end handling parse text match by name, decode arguments with the ABI

Using custom errors

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

error InsufficientBalance(uint256 available, uint256 required);
error ZeroAmount();

contract Wallet {
    mapping(address => uint256) public balance;

    function deposit(uint256 amount) external {
        if (amount == 0) revert ZeroAmount();
        balance[msg.sender] += amount;
    }

    function spend(uint256 amount) external {
        uint256 available = balance[msg.sender];
        if (amount > available) revert InsufficientBalance(available, amount);
        balance[msg.sender] = available - amount;
    }
}

contract Main {
    function main() external {
        Wallet w = new Wallet();
        w.deposit(40);
        w.spend(15);
        console.log("left:", w.balance(address(this)));
        w.spend(30);
    }
}
left: 25
main() failed: custom error InsufficientBalance(25, 30)

The playground decodes the error data with the contract's ABI and shows its name and arguments, just like Hardhat, Foundry and block explorers do.

require with a custom error

Since Solidity 0.8.26, require also accepts a custom error as its second argument, combining the readability of require with the efficiency of custom errors:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

import "hardhat/console.sol";

contract Gate {
    address public owner = msg.sender;

    error Unauthorized(address caller);

    function open() external view returns (string memory) {
        require(msg.sender == owner, Unauthorized(msg.sender));
        return "gate opened";
    }
}

contract Visitor {
    function knock(Gate gate) external view returns (string memory) {
        return gate.open();
    }
}

contract Main {
    function main() external {
        Gate gate = new Gate();
        console.log(gate.open());
        Visitor visitor = new Visitor();
        console.log("visitor is", address(visitor));
        visitor.knock(gate);
    }
}
gate opened
visitor is 0xB7A5bd0345EF1Cc5E66bf61BdeC17D2461fBd968
main() failed: custom error Unauthorized(0xB7A5bd0345EF1Cc5E66bf61BdeC17D2461fBd968)

Errors declared inside a contract (like Gate.Unauthorized) and errors declared at file level both work. The revert data passes unchanged through Visitor up to Main, which is why the original error and address appear.

Catching errors in code

When one contract calls another, it can react to specific errors with try … catch (covered in the try / catch lesson). Low-level calls return the raw error data, whose first four bytes are the error's selector:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Vault {
    error Locked(uint256 until);
    uint256 public unlockTime = block.timestamp + 30 days;

    function withdraw() external view {
        if (block.timestamp < unlockTime) revert Locked(unlockTime);
    }
}

contract Main {
    function main() external {
        Vault vault = new Vault();
        (bool ok, bytes memory data) = address(vault).call(abi.encodeCall(Vault.withdraw, ()));
        console.log("ok?", ok);
        console.log("error data length:", data.length);
        console.log("is Locked error?", bytes4(data) == Vault.Locked.selector);
    }
}
ok? false
error data length: 36
is Locked error? true

The data is 36 bytes: a 4-byte selector plus one 32-byte argument. Vault.Locked.selector gives the selector of an error at compile time.

Naming and style

  • Name errors after what went wrong: NotOwner, DeadlinePassed, AlreadyVoted, InsufficientAllowance.
  • Include the values a user needs to fix the problem: the required amount, the deadline, the offending address.
  • Standards define error names too. ERC-6093 specifies ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed) and friends, which OpenZeppelin's token contracts use.

Test yourself

What is the main advantage of custom errors over revert strings?

  1. They can't be caught
  2. They are cheaper and can carry typed values
  3. They stop the whole blockchain
  4. They don't undo state changes

How do you raise error TooLate(uint256 deadline);?

  1. throw TooLate(d);
  2. revert TooLate(d);
  3. emit TooLate(d);
  4. require TooLate(d);

How long is the revert data of revert Locked(uint256 until)?

  1. 4 bytes
  2. 32 bytes
  3. 36 bytes
  4. 64 bytes