- Home
- Skills
- Zhanghandong
- Rust Skills
- M06 Error Handling
m06-error-handling_skill
- Shell
565
GitHub Stars
1
Bundled Files
2 months ago
Catalog Refreshed
4 months ago
First Indexed
Readme & install
Copy the install command, review bundled files from the catalogue, and read any extended description pulled from the listing source.
Installation
Preview and clipboard use veilstrat where the catalogue uses aiagentskills.
npx veilstrat add skill zhanghandong/rust-skills --skill m06-error-handling- SKILL.md4.5 KB
Overview
This skill codifies Rust error-handling guidance for deciding between Result, Option, panic, and error libraries. It focuses on practical choices: when to propagate, when to add context, and when panicking is appropriate. Use it to align code with library vs application boundaries and to avoid common anti-patterns.
How this skill works
The skill inspects failure semantics and the callsite responsibility to recommend a pattern: Option for normal absence, Result for recoverable errors, and panic/assert for invariant violations. It recommends crates (thiserror for libraries, anyhow for applications), use of ? for propagation, and .context() when additional context is needed. It also maps common mistakes to concrete fixes and traces decisions up and down the design stack.
When to use it
- Choosing between Result<T, E> and Option<T> when designing APIs
- Deciding whether to propagate errors with ? or handle them locally
- Designing library boundaries and selecting thiserror vs anyhow
- Adding context to propagated errors using .context()
- Auditing code for unwrap/expect/panic anti-patterns
Best practices
- Ask: is this failure expected, an absence, or a bug before picking a strategy
- Use Option<T> when absence is a normal outcome; use Result<T, E> for recoverable failures
- Library code: define typed errors with thiserror; application code: use anyhow for ergonomics
- Propagate errors with ? and add .context("what happened") where caller needs more info
- Avoid unwrap() in production; reserve panic!/assert! for true invariants or unrecoverable states
Example use cases
- Implementing a crate API: define explicit thiserror variants for consumers
- CLI application: use anyhow and .context() to present useful error messages to users
- Refactoring code that panics on missing config: switch to Result and surface error to caller
- Fixing unwrap-related panics by replacing unwrap() with ? or a match and a clear error
- Choosing Box<dyn Error> vs typed errors: prefer typed errors unless granularity is unnecessary
FAQ
Use panic! only for violated invariants or unrecoverable bugs. If the failure can reasonably be handled or reported to a caller, return Result.
Should libraries use anyhow for errors?
Prefer thiserror for library boundaries so consumers get typed errors. You can use anyhow internally in applications for ergonomics.