m06-error-handling
actionbook/rust-skills
Master Rust error handling: when to use Result, Option, panic, and how to propagate errors effectively.
What is m06-error-handling?
This skill covers Rust's error handling fundamentals, helping you decide between Result, Option, and panic based on whether failures are expected, normal absence, or bugs. Use it when working with error propagation, custom error types, and designing error strategies for libraries vs applications.
- Distinguish between expected failures (Result), normal absence (Option), and bugs (panic)
- Choose appropriate error handling patterns: thiserror for libraries, anyhow for applications
- Propagate errors with context using the ? operator and .context()
- Design typed error variants that communicate intent to callers
- Identify and fix anti-patterns like unwrap() in production code
How to install m06-error-handling
npx skills add https://github.com/actionbook/rust-skills --skill m06-error-handlingHow to use m06-error-handling
- 1.Identify whether a failure is expected, normal absence, or a bug
- 2.Consult the decision flowchart to choose Result, Option, or panic
- 3.For Result types in libraries, use thiserror to define typed error variants
- 4.For Result types in applications, use anyhow for ergonomic error handling
- 5.Use ? to propagate errors and .context() to add caller-relevant information
- 6.Replace unwrap() with expect() (with reason) or ? in production code
Use cases
- Deciding whether to return Result<T, E> or Option<T> for a function
- Adding context to errors during propagation in application code
- Designing custom error types for a library using thiserror
- Refactoring code with excessive unwrap() calls to use proper error handling
- Choosing between panic!, expect(), and Result when invariants may be violated
- Rust developers writing libraries or applications
- Teams establishing error handling conventions
- Developers migrating from languages with different error models
- Anyone debugging panics or lost error context in production
m06-error-handling FAQ
Use Option when absence is normal (like find/get operations). Use Result when failure is unexpected but recoverable, and you need to communicate why it failed.
Use thiserror in libraries to provide typed errors that consumers can match on. Use anyhow in applications for ergonomic error handling with context chains.
Only in tests, examples, or during development. In production code, use expect() with a reason if you're certain the value exists, or use ? to propagate the error.
Use .context("what was happening") on Result types when using anyhow, or design error variants that capture relevant information when using thiserror.
Panic only for bugs or invariant violations (impossible states). Return Result for expected failures that callers might recover from.
Full instructions (SKILL.md)
Source of truth, from actionbook/rust-skills.
name: m06-error-handling description: "CRITICAL: Use for error handling. Triggers: Result, Option, Error, ?, unwrap, expect, panic, anyhow, thiserror, when to panic vs return Result, custom error, error propagation, 错误处理, Result 用法, 什么时候用 panic" user-invocable: false
Error Handling
Layer 1: Language Mechanics
Core Question
Is this failure expected or a bug?
Before choosing error handling strategy:
- Can this fail in normal operation?
- Who should handle this failure?
- What context does the caller need?
Error → Design Question
| Pattern | Don't Just Say | Ask Instead |
|---|---|---|
| unwrap panics | "Use ?" | Is None/Err actually possible here? |
| Type mismatch on ? | "Use anyhow" | Are error types designed correctly? |
| Lost error context | "Add .context()" | What does the caller need to know? |
| Too many error variants | "Use Box<dyn Error>" | Is error granularity right? |
Thinking Prompt
Before handling an error:
-
What kind of failure is this?
- Expected → Result<T, E>
- Absence normal → Option<T>
- Bug/invariant → panic!
- Unrecoverable → panic!
-
Who handles this?
- Caller → propagate with ?
- Current function → match/if-let
- User → friendly error message
- Programmer → panic with message
-
What context is needed?
- Type of error → thiserror variants
- Call chain → anyhow::Context
- Debug info → anyhow or tracing
Trace Up ↑
When error strategy is unclear:
"Should I return Result or Option?"
↑ Ask: Is absence/failure normal or exceptional?
↑ Check: m09-domain (what does domain say?)
↑ Check: domain-* (error handling requirements)
| Situation | Trace To | Question |
|---|---|---|
| Too many unwraps | m09-domain | Is the data model right? |
| Error context design | m13-domain-error | What recovery is needed? |
| Library vs app errors | m11-ecosystem | Who are the consumers? |
Trace Down ↓
From design to implementation:
"Expected failure, library code"
↓ Use: thiserror for typed errors
"Expected failure, application code"
↓ Use: anyhow for ergonomic errors
"Absence is normal (find, get, lookup)"
↓ Use: Option<T>
"Bug or invariant violation"
↓ Use: panic!, assert!, unreachable!
"Need to propagate with context"
↓ Use: .context("what was happening")
Quick Reference
| Pattern | When | Example |
|---|---|---|
Result<T, E> | Recoverable error | fn read() -> Result<String, io::Error> |
Option<T> | Absence is normal | fn find() -> Option<&Item> |
? | Propagate error | let data = file.read()?; |
unwrap() | Dev/test only | config.get("key").unwrap() |
expect() | Invariant holds | env.get("HOME").expect("HOME set") |
panic! | Unrecoverable | panic!("critical failure") |
Library vs Application
| Context | Error Crate | Why |
|---|---|---|
| Library | thiserror | Typed errors for consumers |
| Application | anyhow | Ergonomic error handling |
| Mixed | Both | thiserror at boundaries, anyhow internally |
Decision Flowchart
Is failure expected?
├─ Yes → Is absence the only "failure"?
│ ├─ Yes → Option<T>
│ └─ No → Result<T, E>
│ ├─ Library → thiserror
│ └─ Application → anyhow
└─ No → Is it a bug?
├─ Yes → panic!, assert!
└─ No → Consider if really unrecoverable
Use ? → Need context?
├─ Yes → .context("message")
└─ No → Plain ?
Common Errors
| Error | Cause | Fix |
|---|---|---|
unwrap() panic | Unhandled None/Err | Use ? or match |
| Type mismatch | Different error types | Use anyhow or From |
| Lost context | ? without context | Add .context() |
cannot use ? | Missing Result return | Return Result<(), E> |
Anti-Patterns
| Anti-Pattern | Why Bad | Better |
|---|---|---|
.unwrap() everywhere | Panics in production | .expect("reason") or ? |
| Ignore errors silently | Bugs hidden | Handle or propagate |
panic! for expected errors | Bad UX, no recovery | Result |
| Box<dyn Error> everywhere | Lost type info | thiserror |
Related Skills
| When | See |
|---|---|
| Domain error strategy | m13-domain-error |
| Crate boundaries | m11-ecosystem |
| Type-safe errors | m05-type-driven |
| Mental models | m14-mental-model |
Related skills
More from actionbook/rust-skills and the wider catalog.

m07-concurrency
Master Rust concurrency: threads, async/await, channels, and thread-safe primitives.

m09-domain
Model domain concepts as Entities, Value Objects, and Aggregates using Rust ownership and type safety.

m10-performance
Measure, identify bottlenecks, then optimize with data structures, allocation strategies, and parallelism.

m11-ecosystem
Navigate Rust crate selection, dependency management, and ecosystem integration decisions.

m12-lifecycle
Design resource creation, usage, and cleanup patterns using RAII, Drop, and lifecycle strategies.

m13-domain-error
Design domain error handling with categorization, recovery strategies, and resilience patterns.