Skip to content

Instantly share code, notes, and snippets.

@johnnyshankman
Last active May 2, 2023 16:59
Show Gist options
  • Save johnnyshankman/7c10d5699992e10daa56f1d7829f4ac4 to your computer and use it in GitHub Desktop.
Save johnnyshankman/7c10d5699992e10daa56f1d7829f4ac4 to your computer and use it in GitHub Desktop.
Catch and assert the value of any custom error thrown by a smart contract in Truffle unit testing by using just the built in web3.js module
const expectCustomRevertError = async function(promise, expectedErrorSignature) {
try {
await promise;
} catch (error) {
const encoded = web3.eth.abi.encodeFunctionSignature(expectedErrorSignature);
const returnValue = Object.entries(error.data).filter(it=>it.length>1).map(it=>it[1]).find(it=>it!=null && it.constructor.name==="Object" && "return" in it).return
assert.equal(returnValue, encoded);
return;
}
expect.fail('Expected an exception but none was received');
}
// Usage
await expectCustomRevertError(
contract.someMethod(),
"TheCustomError()" // In Solidity: error TheCustomError();
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment