PluginBench
Skill
Pass
Audit score 90

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-handling
Claude Code
Cursor
Windsurf
Cline

How to use m06-error-handling

  1. 1.Identify whether a failure is expected, normal absence, or a bug
  2. 2.Consult the decision flowchart to choose Result, Option, or panic
  3. 3.For Result types in libraries, use thiserror to define typed error variants
  4. 4.For Result types in applications, use anyhow for ergonomic error handling
  5. 5.Use ? to propagate errors and .context() to add caller-relevant information
  6. 6.Replace unwrap() with expect() (with reason) or ? in production code

Use cases

Good for
  • 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
Who it's for
  • 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

When should I use Result vs Option?

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.

Should I use thiserror or anyhow?

Use thiserror in libraries to provide typed errors that consumers can match on. Use anyhow in applications for ergonomic error handling with context chains.

Is it ever okay to use unwrap()?

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.

How do I add context to errors?

Use .context("what was happening") on Result types when using anyhow, or design error variants that capture relevant information when using thiserror.

When should I panic vs return Result?

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

PatternDon't Just SayAsk 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:

  1. What kind of failure is this?

    • Expected → Result<T, E>
    • Absence normal → Option<T>
    • Bug/invariant → panic!
    • Unrecoverable → panic!
  2. Who handles this?

    • Caller → propagate with ?
    • Current function → match/if-let
    • User → friendly error message
    • Programmer → panic with message
  3. 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)
SituationTrace ToQuestion
Too many unwrapsm09-domainIs the data model right?
Error context designm13-domain-errorWhat recovery is needed?
Library vs app errorsm11-ecosystemWho 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

PatternWhenExample
Result<T, E>Recoverable errorfn read() -> Result<String, io::Error>
Option<T>Absence is normalfn find() -> Option<&Item>
?Propagate errorlet data = file.read()?;
unwrap()Dev/test onlyconfig.get("key").unwrap()
expect()Invariant holdsenv.get("HOME").expect("HOME set")
panic!Unrecoverablepanic!("critical failure")

Library vs Application

ContextError CrateWhy
LibrarythiserrorTyped errors for consumers
ApplicationanyhowErgonomic error handling
MixedBoththiserror 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

ErrorCauseFix
unwrap() panicUnhandled None/ErrUse ? or match
Type mismatchDifferent error typesUse anyhow or From
Lost context? without contextAdd .context()
cannot use ?Missing Result returnReturn Result<(), E>

Anti-Patterns

Anti-PatternWhy BadBetter
.unwrap() everywherePanics in production.expect("reason") or ?
Ignore errors silentlyBugs hiddenHandle or propagate
panic! for expected errorsBad UX, no recoveryResult
Box<dyn Error> everywhereLost type infothiserror

Related Skills

WhenSee
Domain error strategym13-domain-error
Crate boundariesm11-ecosystem
Type-safe errorsm05-type-driven
Mental modelsm14-mental-model