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 ScStatus
, containing the integer value of the error as contract error.
{ "status": { "contractError": 1 } }
Guides in this category:
📄️ 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.
📄️ Upgrade the Wasm bytecode of a deployed contract
Upgrade the Wasm bytecode of a deployed contract
📄️ Write metadata for your contract.
Write structured metadata.