2

How can I catch exception thrown by method call?

(async () => {
   try {
      const contract = await MyContract.deployed();

      const gasPrice = await web3.eth.getGasPrice();

      contract.methods
        .myMethod()
        .send({ from: account, gasPrice });  // gas: 200000,
   } catch (e) {
      console.log(e);
   }
})()

For some reason I'm not able to cache error thrown by this code. I've tried different ways like using .on('error') and .catch but nothing works.

(node:7042) UnhandledPromiseRejectionWarning: Error: "gas" is missing
at signed (/Users/dimitry/Workspace/contract/node_modules/web3-eth-accounts/src/index.js:165:21)
at /Users/dimitry/Workspace/contract/node_modules/web3-eth-accounts/src/index.js:259:16
at process.internalTickCallback (internal/process/next_tick.js:77:7)

I'm using "web3": "^1.0.0-beta.37"

Thanks.

Dimitry
  • 21
  • 1
  • 2

1 Answers1

2

You also need determinate the gas usage, you can use:

web3.eth.estimateGas(callObject [, callback])

Try this:

(async () => {
   try {
      const contract = await MyContract.deployed();
      const gasPrice = await web3.eth.getGasPrice();
      const gasEstimate = await contract.methods.myMethod().estimateGas({ from: account });

      contract.methods
        .myMethod()
        .send({ from: account, gasPrice: gasPrice, gas: gasEstimate });
   } catch (e) {
      console.log(e);
   }
})()
Alfredo Egaf
  • 321
  • 3
  • 9