I have a very simple React app that calls a Solidity smart contract’s method using Web3.js (4.3.2
) with some data coming from a form. I’m trying to catch errors while calling the contract method or sending the transaction, such as the user closing the wallet modal, in order to display an error message.
This is the setup code (simplified):
window.ethereum.request({ method: "eth_requestAccounts" });
const web3 = new Web3(window.ethereum);
const factoryCampaignContract = new web3.eth.Contract(CAMPAIGN_ABI, CAMPAIGN_ADDRESS);
In the form’s submit handler I’ve tried 3 different options to catch the error.
try-catch
try {
const receipt = await factoryCampaignContract.methods
.createCampaign(minimumContribution)
.send({ from: accounts[0] });
} catch(err) {
console.log(err);
}
.then()
+ .catch()
factoryCampaignContract.methods
.createCampaign(minimumContribution)
.send({ from: accounts[0] })
.then(receipt => console.log(receipt))
.catch(err => console.log(err));
factoryCampaignContract.methods
.createCampaign(minimumContribution)
.send({ from: accounts[0] })
.on('transactionHash', (hash) => console.log(hash))
.on('confirmation', (confirmationNumber) => console.log(confirmationNumber))
.on('receipt', (receipt) => console.log(receipt))
.on('error', (error) => console.log(error));
As soon as I close the wallet modal, I see the following error in the console, but none of the blocks above where the error should have been caught are actually invoked:
Uncaught (in promise) Error: User rejected the request.
at ap.<anonymous> (<anonymous>:7:4040)
at Generator.next (<anonymous>)
at u (<anonymous>:1:1048)