agentleFS
saizulsaizul/rust-dev-skills/skills/rust-error-handling/SKILL.md

rust-error-handling

Skill0 starsChanged 3 days agoMITView on GitHub

Design and clean up Rust error handling with thiserror and anyhow - typed error enums for libraries (from/source chains, non_exhaustive, no stringly errors), anyhow with context for binaries, the ? operator, converting at crate boundaries, and replacing unwrap/expect/panic in production paths. Includes a scanner that skips test code and reports unwrap(), empty expect(), todo!/unimplemented!, anyhow or Box dyn Error in a library's public API, Result with String errors, map_err that discards the source and .ok() that swallows errors. Use when the user asks thiserror vs anyhow, how to define an error type, to remove unwraps, why an error message lost its cause, or to review error handling before a release.

6 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use rust-performance.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • huialiSkill

    rust-performance

    Performance optimization expert covering profiling, benchmarking, memory allocation, SIMD, cache optimization, false sharing, lock contention, and NUMA-aware programming.

    Also in 3 projects that use this

The file

Files
SKILL.md

Rust error handling

Goal: libraries return typed errors callers can match on; applications attach context and print a full cause chain; panics are reserved for broken invariants.

Paths below are relative to this skill's folder (in Claude Code: ${CLAUDE_SKILL_DIR}).

When to use

  • "Should I use thiserror or anyhow?", "how do I define my own error type?"
  • "Get rid of the unwraps", "this panics in production"
  • Error messages without the underlying cause ("failed to load config" and nothing else)
  • Reviewing a crate's public error API before publishing

When not to use

  • A compile error about ? and From conversions you need explained: rust-borrow-checker (diag_summary.py gives the E0277 hint), then come back here for the design
  • Panics inside unsafe code or FFI: rust-unsafe-review

Workflow

  1. Classify the crate: library (others call it, src/lib.rs), application (src/main.rs), or both. The rule: libraries -> thiserror enums, binaries -> anyhow.
  2. Scan (read-only; tests, benches and examples are skipped):
    python3 scripts/error_scan.py .                    # or a crate dir / file
    python3 scripts/error_scan.py . --json --fail-on high
    python3 scripts/error_scan.py . --min-severity medium
    In binaries unwrap() is reported as low, in libraries as medium. A trailing // error-scan: allow comment silences one line (for reviewed invariants).
  3. Design the library error type with references/patterns.md: one enum per crate (or per module for large crates), variants named after what failed, #[from] only where the conversion is unambiguous, #[source] to keep the cause, #[non_exhaustive] on published enums. Do not put the source's message into #[error("...")] and also return it as source() (it prints twice).
  4. Application side: anyhow::Result in main and command handlers, .context() / .with_context(|| format!(...)) at every I/O or parse boundary, print with {:#} or {:?} to get the chain, see references/patterns.md.
  5. Replace unwraps one by one, choosing per site:
    • can fail at runtime (I/O, parsing, user input) -> ? plus context or a variant
    • cannot fail by construction -> expect("why it cannot fail")
    • Option -> ok_or(Error::Missing)?, ok_or_else(..), or let Some(x) = .. else { .. } Show the diff per file; do not change public signatures without telling the user it is a breaking change.
  6. Verify: cargo check --all-targets, cargo test, then re-run the scanner. Optional clippy lints to keep it clean: unwrap_used, expect_used, panic, todo (see the rust-lint-ci skill).

Decision points

QuestionAnswer
Callers need to react differently to failures?enum variants (thiserror)
Only reporting to a human?anyhow (applications), or one opaque error struct in a library
Library wants to hide internals?struct with private kind enum + kind() accessor
Error crosses threads / tasks?make it Send + Sync + 'static (anyhow already is)
Box<dyn Error> in a library?replace; callers cannot match or downcast reliably
no_std?thiserror 2 supports no_std with default-features = false

Output

error_scan: 14 findings -> 3 (reviewed invariants marked with error-scan: allow)
Library crate `parser`: new ParseError enum (Io, Syntax { line }, InvalidPort(ParseIntError))
Public API change: parse() now returns Result<Config, ParseError> (breaking, bump minor for 0.x)
Binary `cli`: anyhow with context on file reads; main prints the full chain

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.