如何在web3js中解析智能合约抛出的自定义错误?
Web3.js 获取智能合约自定义错误信息的实现方法
当使用Web3.js调用合约抛出如MY_ERROR()这类自定义错误时,框架不会自动解析返回的错误信息,需要手动解码错误对象中携带的编码数据。以下是具体实现步骤:
前提准备
- 确保使用Web3.js v1.8.0及以上版本,低版本对自定义错误的解码支持有限。
- 合约ABI必须包含自定义错误的定义(比如
MY_ERROR的ABI片段),否则无法完成解码。
实现代码示例
1. 合约定义(参考)
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Dummy { error MY_ERROR(); function foo() external pure { revert MY_ERROR(); } }
2. Web3.js 错误捕获与解码
const Web3 = require('web3'); const web3 = new Web3('YOUR_PROVIDER_URL'); // 包含自定义错误的合约ABI const dummyAbi = [ { "inputs": [], "name": "MY_ERROR", "type": "error" }, { "inputs": [], "name": "foo", "outputs": [], "stateMutability": "pure", "type": "function" } ]; const dummyContract = new web3.eth.Contract(dummyAbi, 'YOUR_CONTRACT_ADDRESS'); async function callFoo() { try { await dummyContract.methods.foo().call(); } catch (error) { // 提取错误的编码数据(适配不同错误结构) let errorData = error.data; if (!errorData && error.message) { const match = error.message.match(/0x[a-fA-F0-9]+/); errorData = match ? match[0] : null; } if (!errorData) { console.log('未提取到错误编码数据'); return; } // 匹配ABI中的自定义错误定义 const targetErrorAbi = dummyAbi.find(item => item.type === 'error' && item.name === 'MY_ERROR'); if (targetErrorAbi) { try { // 解码自定义错误 const decodedError = web3.eth.abi.decodeError(targetErrorAbi, errorData); console.log('捕获到自定义错误:', decodedError.name); // 此处可添加对应错误的业务处理逻辑 } catch (decodeErr) { console.log('错误解码失败:', decodeErr); } } else { console.log('ABI中未定义目标错误'); } } } callFoo();
关键说明
- 错误编码数据通常存在于
error.data中,部分场景下可能需要从error.message中提取(通过正则匹配0x开头的十六进制字符串)。 - 使用
web3.eth.abi.decodeError方法解码,需传入对应错误的ABI片段和编码数据。 - 若为发送交易(而非
call只读调用),错误处理逻辑完全一致,交易失败的错误信息同样会携带编码后的自定义错误数据。
内容的提问来源于stack exchange,提问作者Yash
相关产品推荐
相关产品推荐

