Custom Error Enums
Custom error enums translate business failures into stable u32 codes. Anchor publishes them in IDL; native programs should ship equivalent JSON for @solana/kit 7.0.0 clients.
Recipe
#[repr(u32)]
pub enum VaultError {
InsufficientFunds = 6000,
SlippageExceeded = 6001,
}When to reach for this:
- Building user-facing dApps that show specific errors.
- Supporting i18n error messages off-chain.
- Auditing failure modes.
Working Example
#[error_code]
pub enum Error {
#[msg("Insufficient funds")]
InsufficientFunds,
#[msg("Slippage exceeded")]
SlippageExceeded,
}What this demonstrates:
- Anchor attribute generates codes + IDL.
- Msg strings are off-chain hints.
- Stable ordering matters.
Deep Dive
Code Ranges
- Anchor: 6000+
- Native: pick unused range per program
IDL Export
Clients decode name + code.
Rust Notes
return Err(Error::InsufficientFunds.into());Gotchas
- Reorder enum - Changes codes - client break.. Fix: Append only.
- Duplicate codes across programs - Log confusion in multi-CPI tx.. Fix: Namespace in UI by program id.
- Leak exploit hints in msg - Detailed msg strings public.. Fix: Generic user text off-chain.
- Too granular - Hundreds of codes hard to maintain.. Fix: Group logically.
- No IDL publish - Clients show unknown error.. Fix: CI publish IDL artifact.
Alternatives
| Alternative | Use When | Don't Use When |
|---|---|---|
| Builtin ProgramError only | Internal programs | UX |
| String errors | Not on-chain | N/A |
| Events for failures | Wrong tool | Use errors |
FAQs
Anchor msg attribute?
Metadata for IDL.
Native IDL?
Hand-write or Codama.
i18n?
Map code to locale off-chain.
Simulation?
Returns same custom code.
Error in CPI?
May see callee code in logs.
u32 max?
Practical limit smaller.
thiserror?
Host cfg tests.
Fuzz?
All branches return Err not panic.
6000 reserved?
Anchor convention.
Multiple programs?
Program id + code tuple.
IDL version?
Tag releases.
Kit decoder?
@solana/kit 7.0.0 helpers.
Related
- Error Handling On-Chain - Patterns
- Decoding Errors Off-Chain - Clients
- Error Code & require! - Anchor 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.