agentleFS
botirkhaltaevbotirkhaltaev/botir-skills/skills/rust-error-handling/SKILL.md

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
  1. Distinctive:

    Keep variants domain-specific and actionable

    line 69

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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, and Option
  • Designing custom error types for a library or application
  • Composing multiple error types with ?
  • Deciding between thiserror (libraries) and anyhow (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 Display for 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
MethodPurpose
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

MethodPurpose
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!() over unwrap())

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, conversion
  • references/custom-errors.md — designing error enums, thiserror patterns
  • references/anyhow-context.md — application-level error handling, context chains

Key References

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.