web3jsmetamask

How to get the MetaMask error object when getting an error while using web3js


When I call a function like so:

try {
  contract.methods[methodName]().estimateGas({from: account, value: x, gas: '5000000'})
  .catch((error) => {
    console.log(error);
  })
  return true;
} catch (e: any) {
    console.log(error);
}

inpage.js of MetaMask will print this to the console:

    inpage.js:1 MetaMask - RPC Error: Internal JSON-RPC error. 
{code: -32603, message: 'Internal JSON-RPC error.', data: {…}}
code
: 
-32603
data
: 
{code: -32000, message: 'err: insufficient funds for gas * price + value: a…3 want 1000000000000000000 (supplied gas 2510499)'}
message
: 
"Internal JSON-RPC error."
[[Prototype]]
: 
Object

But my try catch and .catch will print:

page.tsx:314 ResponseError: Returned error: Internal JSON-RPC error.
    at Web3RequestManager.eval (webpack-internal:///(app-client)/./node_modules/web3-core/lib/esm/web3_request_manager.js:129:19)
    at Generator.next (<anonymous>)
    at fulfilled (webpack-internal:///(app-client)/./node_modules/web3-core/lib/esm/web3_request_manager.js:31:58)

How can I get actual error printed by MetaMask including the object in data?


Solution

  • In (ts) import ResponseError from web3js and call .data or .code on it like so:

    if (e instanceof ResponseError) {
      console.log(e.data.message);
      console.log(e.code)
    }