rust-error-handling
Skill4 starsChanged 3 months agoApache-2.0View on GitHub
Idiomatic Rust error handling with Result, Option, the ? operator, custom error types, thiserror, and anyhow. Use when designing error hierarchies, composing fallible operations, converting between error types, or choosing between library and application error strategies.
We split this skill into the rules it gives an agent
1 rule. About 0 are common, 1 is distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 69
Keep variants domain-specific and actionable
≈ “Common” is an estimate: at least 1 in 5 of the 308,232 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Rust Error Handling
Comprehensive guide based on The Rust Programming Language Ch. 9, Effective Rust Item 4, and Rust by Example.
When to Use This Skill
- Choosing between
panic!,Result, andOption - Designing custom error types for a library or application
- Composing multiple error types with
? - Deciding between
thiserror(libraries) andanyhow(applications) - Converting errors with
From/Into - Wrapping context around errors
Decision Tree
Is recovery possible?
├── No → panic! / unwrap / expect (bugs, invariant violations)
└── Yes
├── Value might be absent (not an error) → Option<T>
└── Operation can fail → Result<T, E>
├── Library crate → custom enum + thiserror
└── Application → anyhow::Result or Box<dyn Error>The ? Operator
Propagates errors by early-returning Err(e.into()):
use std::fs;
use std::io;
fn read_config() -> Result<String, io::Error> {
let path = fs::read_to_string("config.toml")?; // returns Err on failure
Ok(path)
}? calls From::from(err) on the error, enabling automatic conversion.
Custom Error Types (Library Pattern)
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ParseError {
#[error("invalid header at byte {offset}")]
InvalidHeader { offset: usize },
#[error("unsupported version {0}")]
UnsupportedVersion(u32),
#[error(transparent)]
Io(#[from] std::io::Error),
}Key rules:
- Implement
std::error::Error(thiserror does this automatically) - Implement
Displayfor user-facing messages - Implement
From<SubError>for each wrapped error type - Keep variants domain-specific and actionable
Application Error Pattern (anyhow)
use anyhow::{Context, Result};
fn main() -> Result<()> {
let config = std::fs::read_to_string("app.toml")
.context("failed to read config file")?;
let parsed = parse_config(&config)
.context("config parsing failed")?;
run(parsed)?;
Ok(())
}anyhow provides:
anyhow::Error— type-erased, carries a chain of context.context("msg")— wraps error with human-readable description.with_context(|| format!(...))— lazy context formatting- Downcasting:
err.downcast_ref::<MyError>()
Option Combinators
let port: Option<u16> = env::var("PORT").ok()
.and_then(|s| s.parse().ok());
let port = port.unwrap_or(8080); // default fallback| Method | Purpose |
map(f) | Transform inner value |
and_then(f) | Chain fallible transforms |
unwrap_or(v) | Default value |
unwrap_or_else(f) | Lazy default |
ok_or(e) | Convert to Result |
transpose() | Option<Result> ↔ Result<Option> |
Result Combinators
| Method | Purpose |
map(f) | Transform Ok value |
map_err(f) | Transform Err value |
and_then(f) | Chain fallible operations |
or_else(f) | Try alternative on error |
unwrap_or_default() | Use Default on error |
context("msg") | (anyhow) Add context |
When to panic!
- Invariant violations that indicate bugs (not user input errors)
- Setup/initialization that can't recover (missing required env vars at startup)
- Tests and examples
unreachable!()for logically impossible branches- Prototype code (prefer
todo!()overunwrap())
Error Composition Pattern
#[derive(Debug, Error)]
pub enum AppError {
#[error("database error")]
Db(#[from] diesel::result::Error),
#[error("network error")]
Network(#[from] reqwest::Error),
#[error("validation: {0}")]
Validation(String),
}Reference Map
references/result-option.md— Result/Option APIs, combinators, conversionreferences/custom-errors.md— designing error enums, thiserror patternsreferences/anyhow-context.md— application-level error handling, context chains
Key References
Other versions3 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 3
- opensite-ai/opensite-skills★ 15same name
- adxptived/Rust-Skills★ 1same name
- codecharmhq/claude-code-skills★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository80 other files it gives its agents.
- a11y-accessibility-designSkill
- agentic-ui-patternsSkill
- ai-native-ui-designSkill
- ai-ui-anti-patternsSkill
- ai-ui-heuristicsSkill
- calm-technology-uiSkill
- conversion-growth-designSkill
- cross-platform-designSkill
- dark-mode-designSkill
- data-visualizationSkill
- design-systemsSkill
- design-thinking-processSkill
- error-empty-statesSkill
- ethical-design-patternsSkill
- form-uxSkill
- information-architectureSkill
- interaction-design-patternsSkill
- internationalization-uiSkill
- mobile-touch-designSkill
- modal-classes-lifecycleSkill
- modal-container-imagesSkill
- modal-dicts-queuesSkill
- modal-endpointsSkill
- modal-fundamentalsSkill
- modal-gpu-computeSkill
- modal-networkingSkill
- modal-observabilitySkill
- modal-parallel-executionSkill
- modal-sandboxesSkill
- modal-scaling-performanceSkill
- modal-schedulingSkill
- modal-secretsSkill
- modal-serversSkill
- modal-storageSkill
- modal-web-servingSkill
- modal-workspace-adminSkill
- motion-design-principlesSkill
- notifications-permissionsSkill
- onboarding-uxSkill
- rust-api-designSkill
- rust-async-programmingSkill
- rust-cargo-masterySkill
- rust-cli-applicationsSkill
- rust-clippy-lintsSkill
- rust-closures-iteratorsSkill
- rust-compiler-internalsSkill
- rust-concurrencySkill
- rust-design-patternsSkill
- rust-editionsSkill
- rust-embeddedSkill
- rust-game-developmentSkill
- rust-lifetimes-borrowingSkill
- rust-macrosSkill
- rust-performanceSkill
- rust-rustdocSkill
- rust-rustup-toolchainSkill
- rust-smart-pointersSkill
- rust-testing-benchmarkingSkill
- rust-type-systemSkill
- rust-unsafe-ffiSkill
- The first 60 shown.
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
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.

