Errors & Events Best Practices
Observable, debuggable Anchor programs use typed errors, structured events, and minimal logging.
How to Use This List
- Apply on every public instruction before mainnet.
- Verify indexer parses your chosen emit style.
- Pin IDL error table in client repos.
A - Errors
- Use #[error_code] for all user-facing failures stable codes in IDL.
- Append new variants; do not reorder preserve client mappings.
- Map constraint failures with @ Variant specific messages.
- Simulate txs in clients before send decode errors early.
B - Events and logs
- Emit events for indexable state changes not msg! in production.
- Pick emit vs emit_cpi consistently document for indexer team.
- Gate debug logs behind features save CU on mainnet.
- Keep event payloads small avoid log truncation.
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 errors events bp.
Related
- Events with emit! - events
- #[error_code] & require! - errors
- Codegen Best Practices - IDL sync
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.