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 } }
Guides in this category:
📄️ Using __check_auth in interesting ways
Two guides that walk through using __check_auth
📄️ Making cross-contract calls
Call a smart contract from within another smart contract
📄️ Deploy a contract from installed Wasm bytecode using a deployer contract
Deploy a contract from installed Wasm bytecode using a deployer contract
📄️ Deploy a SAC for a Stellar asset using code
Deploy a SAC for a Stellar asset using Javascript SDK
📄️ Organize contract errors with an error enum type
Manage and communicate contract errors using an enum struct stored as Status values
📄️ Extend a deployed contract’s TTL with code
How to extend the TTL of a deployed contract's Wasm code using JavaScript SDK
📄️ Upgrading Wasm bytecode for a deployed contract
Upgrade Wasm bytecode for a deployed contract
📄️ Write metadata for your contract
Use the contractmeta! macro in Rust SDK to write metadata in Wasm contracts