如何在web3.js 1.5中打印Solidity合约返回的revert错误信息
问题根因
web3.js 1.5.x 版本未内置合约 revert 自定义错误信息的自动解析能力,你拿到的 RPC 返回错误为嵌套压缩结构,需要手动提取解析才能得到 Solidity 中定义的错误内容。
可行解决方案
方案一:手动解析现有错误对象
无需修改依赖版本,直接调整 catch 块代码,对嵌套的错误信息做解析即可拿到目标内容:
async bid(amount) { if(this.state.auction!=='undefined'){ try{ await this.state.auction.methods.bid().send({value: this.state.web3.utils.toWei(amount).toString(), from: this.state.account}) } catch (e) { let revertMsg = "" // 优先匹配revert关键字后的自定义内容 const revertMatch = e.message.match(/revert\s+([^"'\n}]+)/) if (revertMatch) { revertMsg = revertMatch[1].trim() } else { // 嵌套结构解析兜底 try { const errContent = e.message.split('from RPC ')[1] const errObj = JSON.parse(errContent) revertMsg = errObj?.error?.message?.replace('execution reverted: ', '') || "交易执行失败,请检查参数后重试" } catch (parseErr) { revertMsg = "交易执行失败,请检查参数后重试" } } // 此处revertMsg即为Solidity定义的错误信息,可直接渲染到前端 console.log(revertMsg) } } }
方案二:升级web3.js到高稳定版本
如果可以调整项目依赖,将web3.js升级到1.7.4及以上的1.x稳定版,或者4.x版本,这些版本已经内置了revert错误解析能力,直接读取错误对象的reason字段即可拿到自定义错误:
catch (e) { console.log(e.reason) // 直接输出"There already is a higher bid." }
优化体验方案
可以在发送链上交易前,先调用call方法预执行交易,用户不需要支付gas就能提前拿到错误结果:
try{ const txValue = this.state.web3.utils.toWei(amount).toString() // 预执行校验,不发起链上交易 await this.state.auction.methods.bid().call({value: txValue, from: this.state.account}) // 预执行通过再发起真实交易 await this.state.auction.methods.bid().send({value: txValue, from: this.state.account}) } catch (e) { console.log(e.message) // call方法返回的错误会直接携带revert信息 }
内容的提问来源于stack exchange,提问作者brmRush
相关产品推荐
相关产品推荐

