Here is an article on how to retrieve the reverted message string or reason from the ethers.js
library in Solidity:
Getting Reverted Message String or Reason with ethers.js v5
In Solidity, there are statements like revert("some reason")
or require(a < b, "a should be less than b"). To get the error reason string using ethers.js, we need to use the
ethers.utils.revert()function.
Theethers.utils.revert()function returns a promise that resolves with an error object containing information about the reverted transaction. We can then access the error message or reason by calling
error.messageor
error.reason.
Here's an example:
const ethers = require('ethers.js');
// Create a new account
const account = ethers.utils Account.create();
// Revert with a custom reason
ethers.revert({
from: account.address,
to: '0x...',
gas: 100000,
nonce: 1,
value: 10n, // in whey
reason: 'Something went wrong! Please try again later.',
});
// Get the reversed error message or reason
const error = ethers.utils.revert().then((err) => err);
console.log(error.message); // "Something went wrong! Please try again later."
In this example, we create a new account and then use ethers.revert()to revert a transaction with a custom reason. The returned promise resolves with an error object that contains information about the reverted transaction.
By accessing the error message or reason usingerror.messageor
error.reason, we can get valuable insights into what went wrong during the reversion process.
Best Practices
- Always handle errors properly and display them to the user.
- Keep track of the error messages and reasons for later analysis.
- Useethers.utils.revert()` when you need to revert a transaction with a custom reason or message.
- Be aware that ethers.js v5 may have changed its API, so make sure to check the documentation for any changes.
I hope this helps! Let me know if you have any questions or need further assistance.