Skip to main content

Organize contract errors with an error enum type

A convenient way to manage and meaningfully communicate contract errors is to collect them into an enum struct. These errors are a special type of enum integer type that are stored on ledger as Status values containing a u32 code. First, create the Error struct in your smart contract.

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

Then, panic with an error when the conditions are met. This example will panic with the specified error.

#[contractimpl]
impl Contract {
pub fn causeerror(env: Env, error_code: u32) -> Result<(), Error> {
match error_code {
1 => Err(Error::FirstError),
2 => Err(Error::AnotherError),
3 => Err(Error::YetAnotherError),
_ => Err(Error::GenericError),
}
}
}

When converted to XDR, the value becomes an ScVal, containing a ScError, containing the integer value of the error as contract error.

{ "error": { "contractError": 1 } }