Error Handling in Rust

VerifiedSafe

A skill for deciding how to handle errors in Rust using Result, Option, panic, and propagation with ?. Covers thiserror and anyhow for context.

Sby Skills Guide Bot
DevelopmentIntermediate
7/22/2026
Claude CodeCursorCodex
#rust#error-handling#result-option#thiserror#anyhow

Recommended for

Automated summary

A decision guide for picking the right error-handling strategy in Rust: Result, Option, propagation with ?, panic, and when to use thiserror or anyhow.

Strengths

  • Offers a clear decision flowchart starting from "is this failure expected or a bug?"
  • Explicitly separates library code (thiserror) from application code (anyhow) and the mixed case
  • Mapping tables tie concrete symptoms (panicking unwrap, lost context) to the design question to ask instead
  • Covers common anti-patterns alongside their better alternatives

Limitations

  • Focused on language mechanics, with no full code examples or end-to-end project
  • Cross-references to other modules (m09-domain, m13-domain-error) are unusable outside this skills system
  • Not user-invocable, so it must be loaded by the agent rather than called directly
When to use it

Reach for it whenever you need to choose between Result, Option, panic, or an error crate in Rust code.

When not to use it

Skip it for non-Rust code or when the problem is purely algorithmic and unrelated to error propagation.

Security analysis

Safe
Quality score88/100

The skill is a static Rust error-handling reference. It declares no tools and contains no commands, scripts, network calls, file operations, or instructions to exfiltrate data or disable safety.

No concerns found

How this analysis is made

Examples

Choose Result vs Option
In my Rust crate, a lookup function returns Option but the caller needs to know why it failed. Should I switch to Result, and which error type should I use?
Replace unwrap in production code
This Rust file has several .unwrap() calls in production paths. Review them and tell me which should become ?, which should keep expect, and where I need to add context.
Design library errors
I'm writing a Rust library that parses config files. Should I use thiserror or anyhow for my error types, and how granular should the variants be?

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:

  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)

| 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 |

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/error-handling-in-rust-mrwakdlc' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/error-handling-in-rust-mrwakdlc/download' --output '.skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md.part' && mv '.skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md.part' '.skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

Original excerpt: 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")

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md' && test -s '.skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/m06-error-handling' && cp -R '.skill-downloads/error-handling-in-rust-mrwakdlc' '.claude/skills/m06-error-handling'

Cursor
test -f '.skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md' && test -s '.skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/m06-error-handling' && cp -R '.skill-downloads/error-handling-in-rust-mrwakdlc' '.cursor/skills/m06-error-handling'

Codex
test -f '.skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md' && test -s '.skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/m06-error-handling' && cp -R '.skill-downloads/error-handling-in-rust-mrwakdlc' '.agents/skills/m06-error-handling'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/error-handling-in-rust-mrwakdlc'

openskills read 'error-handling-in-rust-mrwakdlc'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/error-handling-in-rust-mrwakdlc/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills