What is the correct way to revert safely with reasons?

In sway, developers can revert using revert(0). Is there a way to revert safely and neatly with specified reasons?

You can use a require statement and add reason as the second params to it

1 Like

Edit: Found the revert with reasons, but still experimental

/// Reverts unconditionally and logs `value`.
///
/// # Arguments
///
/// * `value`: [T] - The value which will be logged.
///
/// # Reverts
///
/// * Reverts unconditionally.
///
/// # Examples
///
/// ```sway
/// fn foo() {
///     revert_with_log("Example error message");
/// }
/// ```
#[cfg(experimental_new_encoding = false)]
pub fn revert_with_log<T>(value: T) {
    log(value);
    revert(REVERT_WITH_LOG_SIGNAL)
}

#[cfg(experimental_new_encoding = true)]
pub fn revert_with_log<T>(value: T)
where
    T: AbiEncode,
{
    log(value);
    revert(REVERT_WITH_LOG_SIGNAL)
}

Hi @Nazeeh21, Is there a way to revert with log with reasons?

    // set a fee category id for a strategy that calls this function directly
    #[storage(read, write)]
    fn Strategy_setStratFeeId(_feeId: u64) {
        let _strategy_identity = msg_sender().unwrap();
        let _strategy: ContractId = match _strategy_identity {
            Identity::ContractId(contract_id) => contract_id,
            _ => revert_with_log("Only Contract can call"), // Handle the case where the sender is not a ContractId
        };
        _setStratFeeId(_strategy, _feeId); // Pass the strategy and its corresponding fee ID
    }

The error:

76 |         let _strategy: ContractId = match _strategy_identity {
77 |             Identity::ContractId(contract_id) => contract_id,
78 |             _ => revert_with_log("Only Contract can call this function"), // Handle the case where the sender is not a ContractId

If I only use revert(0), it works:

    // set a fee category id for a strategy that calls this function directly
    #[storage(read, write)]
    fn Strategy_setStratFeeId(_feeId: u64) {
        let _strategy_identity = msg_sender().unwrap();
        let _strategy: ContractId = match _strategy_identity {
            Identity::ContractId(contract_id) => contract_id,
            _ => revert(0), // Handle the case where the sender is not a ContractId
        };
        _setStratFeeId(_strategy, _feeId); // Pass the strategy and its corresponding fee ID
    }

Hey @eesheng, in sway you cant directly use the revert_with_log() instead, you can use the require() statment. In the earlier reply, i meant to say require() and not revert(). Appologies for the confusion

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.