Solidity custom error a way to save gas?

Favorite_blockchain_lady
2 min readJun 16, 2022

On a task I was given at work, I found out that the gas fee was much. I started looking for ways to save gas and I stumbled on something. I reached out to the lead dev and spoke to him about what I found. Custom errors. From my research, they save more gas.

If you know the basics of solidity, the version 0.8.4 has four methods of throwing errors. They are:

  1. Require
  2. Revert
  3. Assert
  4. Custom Error.

To be honest, I didn’t know about custom error and it’s ability to save gas. Yes, it saves gas.

Custom error is better than string error message because the amount of gas depend’s on the length of the string. So by using custom error, we can reduce the amount of gas.

Custom errors are defined using the error statement in a way similar to events.

error CustomErrorName(argument1, argument2);

Custom errors don’t have to be declared inside the contract if you wish. It can be declared outside the contract.

It can also be imported into the contract from another contract.

Below is an example of hoe to use custom error

// SPDX-License-Identifier: GPL-3.0pragma solidity ^0.8.4;contract CustomError {error Denied();address payable owner = payable(msg.sender);     function withdraw() public {        if(msg.sender != owner) {         revert Denied();}      owner.transfer(address(this).balance);}}

If i want to log msg.sender with the error message;

// SPDX-License-Identifier: GPL-3.0pragma solidity ^0.8.4;contract CustomError {   error Denied(address caller);address payable owner = payable(msg.sender);   function withdraw() public {     if(msg.sender != owner) {      revert Denied(msg.sender);}   owner.transfer(address(this).balance);}}

Below is the remix code and the error it gave.

Here is the link to the Part 2 of this article (where the differences were shown). Click here to read.

Don’t forget to add your opinion in the comment box.

see you next time

--

--