Attribute Macro soroban_sdk::contracterror

source ·
#[contracterror]
Expand description

Generates conversions from the repr(u32) enum from/into a Status.

There are some constraints on the types that are supported:

  • Enum must derive Copy.
  • Enum variants must have an explicit integer literal.
  • Enum variants must have a value convertible to u32.

Includes the type in the contract spec so that clients can generate bindings for the type.

Examples

Defining an error and capturing errors using the try_ variant.

use soroban_sdk::{contracterror, contractimpl, Env};

#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
    MyError = 1,
    AnotherError = 2,
}

pub struct Contract;

#[contractimpl]
impl Contract {
    pub fn causeerror(env: Env) -> Result<(), Error> {
        Err(Error::MyError)
    }
}

#[test]
fn test() {
    let env = Env::default();

    // Register the contract defined in this crate.
    let contract_id = env.register_contract(None, Contract);

    // Create a client for calling the contract.
    let client = ContractClient::new(&env, &contract_id);

    // Invoke contract causeerror function, but use the try_ variant that
    // will capture the error so we can inspect.
    let result = client.try_causeerror();
    assert_eq!(result, Err(Ok(Error::MyError)));
}

Testing invocations that cause errors with should_panic instead of try_.

#[test]
#[should_panic(expected = "ContractError(1)")]
fn test() {
    let env = Env::default();

    // Register the contract defined in this crate.
    let contract_id = env.register_contract(None, Contract);

    // Create a client for calling the contract.
    let client = ContractClient::new(&env, &contract_id);

    // Invoke contract causeerror function.
    client.causeerror();
}