#[error_code] & require!
Anchor #[error_code] enums map to stable error codes in the IDL. require! and friends assert conditions with those errors.
Search across all documentation pages
Anchor #[error_code] enums map to stable error codes in the IDL. require! and friends assert conditions with those errors.
#[error_code]
pub enum MyError {
#[msg("Amount must be positive")]
InvalidAmount,
}
require!(amount > 0, MyError::InvalidAmount);
require_eq!(owner, ctx.accounts.authority.key(), MyError::Unauthorized);When to reach for this: You need typed, client-decodable failures.
#[error_code]
pub enum VaultError {
#[msg("Vault is paused")]
Paused,
#[msg("Insufficient balance")]
InsufficientFunds,
#[msg("Math overflow")]
Overflow,
}
pub fn withdraw(ctx: Context<Withdraw>, amount: u64) -> Result<()> {
require!(!ctx.accounts.vault.paused, VaultError::Paused);
require!(ctx.accounts.vault.balance >= amount, VaultError::InsufficientFunds);
ctx.accounts.vault.balance = ctx.accounts.vault.balance
.checked_sub(amount)
.ok_or(VaultError::Overflow)?;
Ok(())
}What this demonstrates:
| Macro | Use |
|---|---|
require! | Boolean condition |
require_eq! / require_ne! | Equality checks |
require_keys_eq! | Pubkey comparisons |
Anchor assigns error codes starting at custom offset; clients decode via IDL.
| Alternative | Use When | Don't Use When |
|---|---|---|
| constraint @ Error | Account validation time | Handler business rules |
| Native custom errors | Non-Anchor | IDL-integrated clients |
Custom codes in IDL plus #[msg] strings.
emit_cpi! costs more CU but improves capture reliability.
Avoid except behind feature flags.
From IDL via Anchor or Codama codegen.
Yes, #[event] types are listed.
Yes with @ MyError::Variant.
Each log line and formatted string.
anchor test expecting error codes.
Yes, but not an API contract; use events.
See Related for errors.
Stack versions: This page was written for Agave 4.1.1, Solana CLI 3.0.10, Anchor 0.32.1, anchor-lang 0.32.1, Rust 1.91.1, @solana/kit 7.0.0, Surfpool 0.12.0, and LiteSVM 0.6.x.
Reviewed by Chris St. John·Last updated Jul 16, 2026