Solidity revert with custom error explained with example !!
Tags: ethereumblockchain, ethereum, remixide, solidity
Published: 2021-06-23 14:20:03

---
title: Solidity revert with custom error explained with example !!
published: true
date: 2021-06-21 12:53:03 UTC
tags: ethereumblockchain,ethereum,remixide,solidity
canonical_url: https://medium.com/coinmonks/solidity-revert-with-custom-error-explained-with-example-d9dff8937ef4
---

### Solidity revert with custom error explained with example !!

Since v0.8.4, Solidity has introduced an additional way to revert a transaction. The new method allows users to define a custom error and pass it while reverting a transaction.

#### Custom error

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

```
error CustomErrorName( **arg1** , **arg2** );
```

Custom errors can be defined on contract level or file level. It can further used inside methods to revert the transaction as:

```
revert CustomError( **arg1, arg2** );
```

Old ways of using revert like **revert()** and **revert(“description”)** are still valid but revert with custom error helps in passing dynamic data with the error and is less expensive for contract deployment.

Natspec documentation can be also added to explain the custom errors in contract.

**Example**

Let’s understand it with a simple example. This contract reverts custom error if value sent in transaction is less than to a preset amount.

```
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;

/// Invalid balance to transfer. Needed `minRequired` but sent `amount`
/// [@param](http://twitter.com/param) sent sent amount.
/// [@param](http://twitter.com/param) minRequired minimum amount to send.
error InvalidAmount (uint256 sent, uint256 minRequired);

contract TestToken {
    mapping(address => uint) balances;
    uint minRequired;
    
    constructor (uint256 _minRequired) {
        minRequired = _minRequired;
    }
    
    function list() public payable {
        uint256 amount = msg.value;
        if (amount < minRequired) {
            revert InvalidAmount({
                sent: amount,
                minRequired: minRequired
            });
        }
        balances[msg.sender] += amount;
    }
}
```

#### Demo using Remix

[**Click here**](https://remix.ethereum.org/#code=Ly8gU1BEWC1MaWNlbnNlLUlkZW50aWZpZXI6IEdQTC0zLjAKcHJhZ21hIHNvbGlkaXR5IF4wLjguNDsKLy8vIEludmFsaWQgYmFsYW5jZSB0byB0cmFuc2Zlci4gTmVlZGVkIGBtaW5SZXF1aXJlZGAgYnV0IHNlbnQgYGFtb3VudGAKLy8vIEBwYXJhbSBzZW50IHNlbnQgYW1vdW50LgovLy8gQHBhcmFtIG1pblJlcXVpcmVkIG1pbmltdW0gYW1vdW50IHRvIHNlbmQuCmVycm9yIEludmFsaWRBbW91bnQgKHVpbnQyNTYgc2VudCwgdWludDI1NiBtaW5SZXF1aXJlZCk7CmNvbnRyYWN0IFRlc3RUb2tlbiB7CiAgICBtYXBwaW5nKGFkZHJlc3MgPT4gdWludCkgYmFsYW5jZXM7CiAgICB1aW50IG1pblJlcXVpcmVkOwogICAgCiAgICBjb25zdHJ1Y3RvciAodWludDI1NiBfbWluUmVxdWlyZWQpIHsKICAgICAgICBtaW5SZXF1aXJlZCA9IF9taW5SZXF1aXJlZDsKICAgIH0KICAgIAogICAgZnVuY3Rpb24gbGlzdCgpIHB1YmxpYyBwYXlhYmxlIHsKICAgICAgICB1aW50MjU2IGFtb3VudCA9IG1zZy52YWx1ZTsKICAgICAgICBpZiAoYW1vdW50IDwgbWluUmVxdWlyZWQpIHsKICAgICAgICAgICAgcmV2ZXJ0IEludmFsaWRBbW91bnQoewogICAgICAgICAgICAgICAgc2VudDogYW1vdW50LAogICAgICAgICAgICAgICAgbWluUmVxdWlyZWQ6IG1pblJlcXVpcmVkCiAgICAgICAgICAgIH0pOwogICAgICAgIH0KICAgICAgICBiYWxhbmNlc1ttc2cuc2VuZGVyXSArPSBhbW91bnQ7CiAgICB9Cn0=) to load above contract into Remix IDE to get a demo of custom error.

Deploy the contract and run test with a value less that minRequired , Information of custom error will appear in Remix Terminal.

![](https://cdn-images-1.medium.com/max/1024/1*mpes5e82283yCdAOWcr3zg.png)

#### **Demo using Hardhat**

Put above code in hardhat project’s contracts directory, compile it. Write a script in scripts directory as:

**deployAndRun.js**

```
const hre = require("hardhat");

async function main() {

  // We get the contract to deploy

  const CError = await hre.ethers.getContractFactory("CustomError");

  const cerr = await CError.deploy(20);

  await cerr.deployed();

  console.log("CustomError deployed to:", cerr.address);

  await cerr.list({value: 16});

}

main()

.then(() => process.exit(0))

.catch(error => {

console.error(error);

process.exit(1);

});
```

Run hardhat node and execute script, it shows custom error details as:

```
% npx hardhat run --network localhost scripts/deployAndRun.js

CustomError deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3

ProviderError: Error: VM Exception while processing transaction: reverted with custom error 'InvalidAmount(16, 20)'
```

**DO YOU KNOW:** You can also compile and deploy contract to hardhat using Remix IDE. Read about [**Remix IDE Hardhat Integration**](https://medium.com/remix-ide/hardhat-integration-with-remix-eb8c30196ab1).

Thanks for reading !!!

**References:**

- [https://docs.soliditylang.org/en/v0.8.5/](https://docs.soliditylang.org/en/v0.8.5/)
- [https://blog.soliditylang.org/2021/04/21/custom-errors/](https://blog.soliditylang.org/2021/04/21/custom-errors/)

* * *