Handling Errors and Exceptions
What are Instructions?
Chapter 4: Handling Errors and Exceptions
Error handling ensures your program is robust. Anchor provides tools to define custom errors and validate conditions.
Key Points:
Define errors with #[error_code].
Use require! for runtime checks.
Return errors via Result<()>.
Code Example:
#[error_code]
pub enum MyError {
#[msg("Account not initialized")]
NotInitialized,
}
pub fn update(ctx: Context<Update>, new_value: u64) -> Result<()> {
require!(ctx.accounts.my_account.is_initialized, MyError::NotInitialized);
// Update logic
Ok(())
}
Interactivity: Trigger different error conditions and see the corresponding error messages.
Last updated