Attribute Macro switchboard_solana::prelude::error_code

#[error_code]
Expand description

Generates Error and type Result<T> = Result<T, Error> types to be used as return types from Anchor instruction handlers. Importantly, the attribute implements From on the ErrorCode to support converting from the user defined error enum into the generated Error.

§Example

use anchor_lang::prelude::*;

#[program]
mod errors {
    use super::*;
    pub fn hello(_ctx: Context<Hello>) -> Result<()> {
        Err(error!(MyError::Hello))
    }
}

#[derive(Accounts)]
pub struct Hello {}

#[error_code]
pub enum MyError {
    #[msg("This is an error message clients will automatically display")]
    Hello,
}

Note that we generate a new Error type so that we can return either the user defined error enum or a ProgramError, which is used pervasively, throughout solana program crates. The generated Error type should almost never be used directly, as the user defined error is preferred. In the example above, error!(MyError::Hello).

§Msg

The #[msg(..)] attribute is inert, and is used only as a marker so that parsers and IDLs can map error codes to error messages.