Solidity - Custom Error
This article introduces the usage of custom error in Solidity, including ways to define errors, usage, and error handling.
Usage
This feature was added after Solidity v0.8.4, which can use a custom error to return the error reason. In the past, we usually used the following methods to throw errors:
1 | require(shouldPass, "MyError"); |
Custom error is used as follows:
1 | // Define custom error |
Custom error can also have parameters
1 | // Define custom error |
The following usage can be thought of as the same
1 | revert("MyError"); |
But actually the names of Error and Panic are special names and cannot be used.
Try-Catch
It is more complicated to use try-catch to catch custom error in the contract. Currently, the following methods can be used:
1 | contract TryCatch { |
Pros and Cons
Pros
- The compiled contract size is relatively small.
- Slightly reduced gas consumption.
- It’s easy to use parameters.
Cons
- Node support is required: For example, Ganache for local development does not support it. The error reason cannot be parsed.
- Requires block explorer support to display: At present, browsers seem to be unable to parse this type of error.
- The support of web3.js and ether.js is not complete, and additional processing is required.
Further Reading
Using Ethers.js to Parse Custom Error
Using Web3.js to Parse Custom Error
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Comment