断言后为什么此Solidity函数返回0?

时间:2018-04-14 20:02:33

标签: ethereum solidity remix

我写过这个函数:

// Function to get an owned token's id by referencing the index of the user's owned tokens.
// ex: user has 5 tokens, tokenOfOwnerByIndex(owner,3) will give the id of the 4th token.
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint _tokenId) {
    // TODO: Make sure this works. Does not appear to throw when _index<balanceOf(_owner), which violates
    //       ERC721 compatibility.
    assert(_index<balanceOf(_owner)); // throw if outside range
    return ownedTokenIds[_owner][_index];
}

当_index为2且_owner运行使得balanceOf(_owner)为0时,该函数在Remix IDE中返回0。我的假设是它不会返回任何东西。我的问题是:

A)为什么在断言失败后返回0?

B)当我使用上述参数运行它时,如何让它不返回0?

谢谢, Vaughn的

1 个答案:

答案 0 :(得分:1)

删除我的其他答案,因为它不正确。

错误处理条件不会在view个函数中冒泡到客户端。它们仅用于恢复区块链上的状态更改事务。对于view函数,处理将停止并返回指定返回类型的初始值0(uint为0,bool为false等)。

因此,必须在客户端上处理view函数的错误处理。如果您需要能够区分有效的0返回值和错误,您可以执行以下操作:

function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint, bool) {
    bool success = _index < balanceOf(_owner);
    return (ownedTokenIds[_owner][_index], success);
}