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:
📄️ Analyzing smart contract cost and efficiency
Several factors influence how quickly and efficiently your smart contracts execute on the Stellar network. This guide will help you understand these factors and provide tips on how to write cost-effective contracts.
📄️ Using __check_auth in interesting ways
Using check_auth in interesting ways
📄️ Deploy a contract from installed Wasm bytecode using a deployer contract
{Deploy a contract from installed Wasm bytecode using a deployer contract}
📄️ Organize contract errors with an error enum type
Manage and communicate contract errors using an enum struct stored as Status values.
📄️ Install and deploy a smart contract with code
Install and deploy a smart contract with code
📄️ Integrate Stellar Assets Contracts
Test and use Stellar assets in a Soroban smart contract
📄️ Upgrading Wasm Bytecode for a Deployed Contract
Upgrading Wasm Bytecode for a Deployed Contract
📄️ Write metadata for your contract
Use the contractmeta! macro in Rust SDK to write metadata in Wasm contracts.