Solidity

當 require 中的條件失敗時,是否可以返回一些東西?

  • October 10, 2022

require當結果中的條件為時,是否可以在契約中的函式內返回 0 false

contract MyContract {
    function initialize() public payable returns (uint) {
       require(10 ** 15 < msg.value); //return 0 if this fails
       return 1; //otherwise return 1
}

好吧,你可以嘗試使用try-catch

目前,Solidity 支持不同類型的 catch 塊,具體取決於錯誤的類型。如果錯誤是由 revert(“reasonString”) 或 require(false, “reasonString”) (或導致此類異常的內部錯誤)引起的,則將執行 catch Error(string memory reason) 類型的 catch 子句.

在 catch 塊中返回您想要的值,如下例所示:

try initialize() returns (uint v) {
       return true;
   } catch Error(string memory /*reason*/) {
       // This is executed in case
       // revert was called inside initialize
       // and a reason string was provided.
       
       return false;
}

因為initialize是應付的,所以需要用funds以正確的方式呼叫它

不,如果require函式被評估為 false,則不會返回任何內容,因為程式碼已停止執行。

請參閱:https ://docs.soliditylang.org/en/v0.8.16/control-structures.html

引用自:https://ethereum.stackexchange.com/questions/137179