如何解析web3js中的自定义错误恢复

问题描述 投票:0回答:1

嘿,所以 web3js 没有告诉我抛出了什么自定义错误。

假设我有以下代码

contract Dummy {
    error MY_ERROR();

    function foo() external pure {
        revert MY_ERROR();
    }
}

使用 web3 调用

foo()
时,它只会给出以下错误响应

{
  "originalError": {
    "code": 3,
    "data": "0x888f5130",
    "message": "execution reverted"
  }
}

ethersjs 支持这一点,所以我猜 web3js 中也一定有一种方法,感谢帮助!

ethereum solidity smartcontracts web3js ethers.js
1个回答
-1
投票

参考这篇文章 https://blog.emn178.cc/en/post/using-web3-js-to-parse-custom-error/

定义一些方法

import { Eip838ExecutionError } from 'web3';
import { decodeContractErrorData } from 'web3-eth-abi';

function parseInnerError(e, contract) {
  if (e?.innerError?.errorSignature) {
    return e.innerError;
  }

  if (!e.innerError) {
    if (e?.data?.data.startsWith('0x')) {
      e.innerError = new Eip838ExecutionError(e.data);
    }
  }
  if (e?.innerError?.data?.startsWith('0x')) {
    decodeContractErrorData(contract._errorsInterface, e.innerError);
  }
  return e.innerError;
}

const KEYS = ['to', 'from', 'nonce', 'gas', 'gasPrice', 'maxPriorityFeePerGas', 'maxFeePerGas', 'data', 'value', 'chainId', 'type', 'accessList'];
async function parseTxError(txHash, web3, contract) {
  const tx = await web3.eth.getTransaction(txHash);
  const request = { };
  KEYS.forEach((key) => {
    request[key] = tx[key];
  });
  if (request.gasPrice) {
    delete request.maxPriorityFeePerGas;
    delete request.maxFeePerGas;
  }
  try {
    await web3.eth.call(request, tx.blockNumber);
    return null;
  } catch (e) {
    return parseInnerError(e, contract);
  }
}

对于你的情况,你可以尝试

try {
  await dummy.methods.foo({ from });
} catch (e) {
  const innerError = parseInnerError(e, dummy);
}
© www.soinside.com 2019 - 2024. All rights reserved.