Custom Error Messages
Use #[msg("...")] on error enum variants for default messages. Clients map error codes to localized copy using the IDL.
Recipe
#[error_code]
pub enum SwapError {
#[msg("Slippage tolerance exceeded")]
SlippageExceeded,
#[msg("Pool is disabled")]
PoolDisabled,
}When to reach for this: You ship user-facing dApps that display program failures.
Working Example
#[error_code]
pub enum StakeError {
#[msg("Stake amount below minimum")]
BelowMinimum,
#[msg("Unlock period not elapsed")]
StillLocked,
}
// constraint errors
#[account(constraint = !pool.disabled @ SwapError::PoolDisabled)]
pub pool: Account<'info, Pool>,What this demonstrates:
- IDL exports error names and codes
- Same code across clusters
- constraint @ maps to variant
- Clients should not parse logs for errors
Deep Dive
Client Mapping
Generate error lookup tables from IDL in TypeScript. Show error.errorCode + mapped message in UI.
Stability
Do not renumber error variants lightly; clients cache mappings.
Gotchas
- Changing variant order - Codes shift breaking clients.. Fix: Append new variants only.
- Generic msg for many cases - Poor UX.. Fix: Split variants.
- Embedding user data in msg macro - Not supported dynamically.. Fix: Use events for details.
- English-only in on-chain msg - Localization is client-side.. Fix: Map codes in UI.
- Relying on log strings - Logs change.. Fix: Decode structured errors.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
| Events for failure context | Rich details | Simple user messages |
| Error metadata off-chain | Localization tables | On-chain canonical codes |
FAQs
Anchor 0.32.1 error format?
Custom codes in IDL plus #[msg] strings.
emit! vs emit_cpi!?
emit_cpi! costs more CU but improves capture reliability.
Should I use msg! on mainnet?
Avoid except behind feature flags.
How do clients get error codes?
From IDL via Anchor or Codama codegen.
Do events appear in IDL?
Yes, #[event] types are listed.
Can constraints return custom errors?
Yes with @ MyError::Variant.
What uses CU in logging?
Each log line and formatted string.
How to test errors?
anchor test expecting error codes.
Are logs consensus data?
Yes, but not an API contract; use events.
Next read?
See Related for error messages.
Related
- #[error_code] & require! - declaration
- Client-Side Error Decoding - TS
- The Anchor IDL - IDL errors section
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.