DEV Community

Odutola Abisoye
Odutola Abisoye

Posted on

Handle Errors With Solidity - Require vs Revert - What you should know in 2022 on Solidity Error

Solidity assert and require are convenience functions that check for conditions. In cases when conditions are not met, they throw exceptions.


REQUIRE

Require is reserved for error-conditions of incorrect input data to functions (when compared to expected/valid input data) that can not be detected until execution time. This correspond to function preconditions in programming language argot. The compiler is unable to help due to the infinite possibilities of input data.

What the REQUIRE Function will do

  • Validate user inputs
  • Validate the response from an external contract
  • Validate state conditions prior to executing state changing operations, for example in an owned contract situation
  • Require is used more often
  • Use at the beginning of the function
  • Allow you to return an error message.
  • Refund any remaining gas to the caller.

CODE EXAMPLE

contract Error {
    function errorRequire(uint _i) public pure {
      require(_i <=10, "i must be greater than 10");
      // code
    }
}
Enter fullscreen mode Exit fullscreen mode

Require should be used to validate conditions such as:

  • inputs
  • conditions before execution
  • return values from calls to other functions

REVERT

Revert is reserved for error-conditions that affect business-logic. For example someone sends a vote when the voting is already close.

What the REVERT Function will do

  • Handle the same type of situations as require(), but with more complex logic like Nested If Statement.
  • Handle the same type of situations as require(), but with more complex logic.
  • Used abort execution and revert state changes
  • Allow you to return an error message.
  • Refund any remaining gas to the caller.

CODE EXAMPLE

contract Error {
    function errorRevert(uint _i) public pure {
        if (_i > 10)
            revert("Input must be greater than 10");
        );
    }
}
Enter fullscreen mode Exit fullscreen mode

Revert is useful when the condition to check is complex. - inputs


SUMMARY

  • Use the require() is used to validate inputs and conditions before execution.
  • Use the revert() is used abort execution and revert state changes

Top comments (0)