Custom Errors in Solidity

Published by Mario Oettler on

Last Updated on 12. June 2023 by Mario Oettler

Solidity provides a convenient and gas-efficient way to display error messages to the user.

Custom errors are declared in the head of the contract and called after a revert statement. The following code sample shows how to use custom errors in Solidity:

pragma solidity 0.8.20;

contract ErrorContract{

    error NotAllowed();
    address public owner;

    constructor(){
        owner = msg.sender;
    }

    function myFunction() public {
        if(msg.sender != owner){
            revert NotAllowed();
        }
    }
}

In line 5, the custom error is declared.

In line 14, the custom error is called after the revert statement.

When calling the function, the output looks like that:

Passing Parameters to Custom Errors in Solidity

It is also possible to pass parameters to custom errors. This allows to return of dynamic values and makes debugging easier. This is a big difference from the require statement. It only allows a static string as a return value.

The following code sample shows how to pass parameters with error messages in Solidity:

pragma solidity 0.8.20;

contract ErrorContract{

    error NotAllowed(address owner, address sender, uint256 a);
    address public owner;

    constructor(){
        owner = msg.sender;
    }

    function myFunction(uint256 _a) public {
        if(msg.sender != owner){
            revert NotAllowed(owner, msg.sender, _a);
        }
    }
}

In line 5, we declare the custom error and state the data types for each parameter.

The result looks like that:

Categories:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select: