我正在使用
web3-react
构建 Web UI,与以太坊 Ganache 网络中运行的智能合约进行交互。
合约有一个方法来创建一个可靠的扇区:
function createSector(uint256 x, uint256 y, uint256 width, uint256 height) public payable {
uint256 price = _calculateSectorPrice(width, height);
Sector memory sector = Sector(x, y, width, height, price);
require(balanceOf(msg.sender) + msg.value >= price, "Insufficient funds");
...
}
当网络调用此方法时,
require
会抛出错误:Insufficient funds
。但 UI 不会收到此特定错误,而是收到 ContractExecutionError: Error happened while trying to execute a function inside a smart contract
。这个错误太笼统了,因为它没有告诉我们真正的错误是什么。
我的web3代码是:
await contract.methods
.createSector(
web3.utils.toBigInt(selectedCells[0].globalI),
web3.utils.toBigInt(selectedCells[0].globalJ),
web3.utils.toBigInt(1),
web3.utils.toBigInt(1),
{ value: web3.utils.fromWei(cellPriceInWei, 'ether') }
)
.send({ from: account.address });
我可以确认,如果我从智能合约中删除
require
,一切都会正常。我的问题是如何从智能合约中捕获错误?
在
try/catch
中,catch
块会捕获任何错误。 “资金不足”具体错误代码:
const callCreateSector = () => {
try {
await contract.methods
.createSector(
web3.utils.toBigInt(selectedCells[0].globalI),
web3.utils.toBigInt(selectedCells[0].globalJ),
web3.utils.toBigInt(1),
web3.utils.toBigInt(1),
{ value: web3.utils.fromWei(cellPriceInWei, "ether") }
)
.send({ from: account.address });
} catch (error) {
if (error.code === -32603 && error.data.code === -32000) {
// This was your error code
console.error("Write error message because of insufficient funds ...");
}
}
};