Suppose I have require(..., "error")
but instead, I want the error message to be "error var" where var
is a variable of type string, or uint.
What should I write?
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityYou can use custom errors:
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
error Unauthorized();
contract VendingMachine {
address payable owner = payable(msg.sender);
function withdraw() public {
if (msg.sender != owner)
revert Unauthorized();
owner.transfer(address(this).balance);
}
// ...
}
In fact, I highly recommend you switch to custom errors. They are a godsend for Ethereum development. Compared to revert reason strings, custom errors are easier to work with, more gas efficient, and more elegant.
you can make your custom errors quite descriptive with vars
contract
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.10;
error InvalidNumber(uint32 required, uint32 passed);
contract CustomErrors{
uint32 private constant magicNumber = 42;
function checkMagicNumber(uint32 _number) public pure {
if (_number != magicNumber)
revert InvalidNumber({
required: magicNumber,
passed: _number
});
// ...
}
// ...
}
result calling function passing 21
[vm]from: 0x5B3...eddC4to: CustomErrors.(constructor)value: 0 weidata: 0x608...a0033logs: 0hash: 0xf34...6204d
transact to CustomErrors.checkMagicNumber pending ...
transact to CustomErrors.checkMagicNumber errored: VM error: revert.
revert
The transaction has been reverted to the initial state.
Error provided by the contract:
InvalidNumber
Parameters:
{
"required": {
"value": "42"
},
"passed": {
"value": "21"
}
}
Debug the transaction to get more information.