1

I have a problem when I interact with an Smart Contract, from a javascript webapp. I can execute the transaction correctly when the status is confirmed, but I cannot get any error response when it fails.

myfunction.myTrans.sendTransaction(
    { from: web3.eth.accounts[0], gas: gas, gasPrice:gasPrice, to:contractaddress, value:web3.toWei(document.getElementById("price").value, "ether") },
    function (error, result) {

      if (!error) {
        console.log(result);

      } else {
        console.log("transaction error");
        console.log(error);
      }

    })

When I get an error on Metamask, and I can see it in EtherScan, I don't get any error response in the code. I only get a result when everything goes Ok (transaction confirmed).

Any idea on how to manage transaction errors?

Thanks in advance!

2
  • Which web3 version do you use?
    – n1c01a5
    Commented Jul 22, 2019 at 22:05
  • web3 0.20.7 (injected by metamask) Commented Jul 23, 2019 at 7:04

2 Answers 2

1

When a transaction is issued, the transaction is sent to a node to be mined and added in a block. After issuing the transaction, if the transaction structure is properly filled with necessary fields, the transaction hash will be returned instantly. If there is any wrong in the given transaction structure like to address is not properly set, the error will be returned. These things will happen for the portion of your given code (below)

function (error, result) {

  if (!error) {
    console.log(result);

  } else {
    console.log("transaction error");
    console.log(error);
  }

}

To get the status (success/fail), you can watch using filter for the latest blocks whether your transaction (received transaction hash) is added in the blocks. When the transaction is added in a new block, the callback of watch will be triggered and you will find the status using eth.getTransactionReceipt(txHash)

Link for filter/watch web3js filter-watch

The below code snippet might be used.

function (err, result) {
  if (err) {
    console.error(err);
    return;
  }
  var txhash = result;
  var filter = web3.eth.filter('latest');
  filter.watch(function(error, result) {
    var receipt = web3.eth.getTransactionReceipt(txhash);
    if (receipt && receipt.transactionHash == txhash) {
        console.log("TransactionStatus ", receipt.status);
    }
  });}
0

You can use try .. catch structure to catch errors and exceptions:

try {

  await myfunction.myTrans.sendTransaction({ from: web3.eth.accounts[0], gas: gas, gasPrice:gasPrice, to:contractaddress, value:web3.toWei(document.getElementById("price").value, "ether") });

} catch(error) {

  console.log(error.message);

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.