Custom Errors in Solidity
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: