agentleFS
dawidpereiradawidpereira/rust-skills/skills/rust-errors/SKILL.md

rust-errors

Skill0 starsChanged 8 months agoMITView on GitHub

Rust error handling patterns with Result, Option, thiserror, and anyhow. Use whenever implementing error types, adding error propagation with ?, choosing between panic and Result, or working with .unwrap()/.expect(). Covers library vs application error strategy, error chaining, context, and custom error types. Also use when seeing unwrap abuse or unclear error propagation in code review.

2 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

3 rules. About 0 are common, 1 is distinctive, and 2 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.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    If you're unsure, it's almost certainly expected — use Result.

    line 24
  2. Distinctive:

    Add context when the error alone doesn't tell the story:

    line 73
  3. Very specific:

    Keep unwrap() only in tests and for invariants you've already validated.

    line 152

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 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

Error Handling

Core Question

Is this failure expected or a bug?

This single question drives every error handling decision:

  • Expected (file not found, invalid input, network timeout) → Result<T, E>
  • Absence (optional value, lookup miss) → Option<T>
  • Bug (violated invariant, impossible state) → panic! / expect()

If you're unsure, it's almost certainly expected — use Result.


Error → Design Question

SymptomDon't Just SayAsk Instead
Unwrap everywhere"Add expect message"What should happen when this fails?
Box<dyn Error> return"It works"Can the caller handle specific errors?
Error type has 15 variants"Be thorough"Are these all distinct failure modes the caller cares about?
.context() on every line"More context is better"What context does the caller actually need?
Panic in library code"Document the panic"Should this be a Result instead?

Quick Decisions

ScenarioUseWhy
Library with typed errors callers match onthiserrorGenerates Error impl, typed variants
Application-level error handlinganyhowEasy context, no custom types needed
Library public API + internal conveniencethiserror public, anyhow internalBest of both
Function can fail in expected waysResult<T, E>Caller decides how to handle
Value may or may not existOption<T>No error info needed
Invariant violated (bug in code)panic! / unreachable!Should never happen in correct code
Test assertionsunwrap() / expect()Panics give clear test failures
One-off script / prototypeanyhow::Result in mainQuick iteration, good error display
CLI tool with source-pointing errorsmietteRich diagnostics with labeled source spans and help text
Application with colorized backtracescolor-eyreEnhanced eyre with span traces and color
User-facing HTTP errorCustom AppError implementing IntoResponseSafe message for users, full context in logs
CLI exit codes0 = success, 1 = error, 2 = usageConvention that scripts and CI rely on

The ? Operator

? is the backbone of Rust error handling. It propagates errors up the call stack, converting types via From automatically.

fn load_config(path: &Path) -> Result<Config, AppError> {
    let content = std::fs::read_to_string(path)?;  // io::Error → AppError via From
    let config: Config = toml::from_str(&content)?; // toml::Error → AppError via From
    Ok(config)
}

Add context when the error alone doesn't tell the story:

use anyhow::Context;

let content = std::fs::read_to_string(path)
    .with_context(|| format!("failed to read config from {}", path.display()))?;

Library vs Application

ContextCratePattern
LibrarythiserrorTyped, matchable errors callers can inspect
ApplicationanyhowEasy propagation with context chains
Boththiserror for public APIanyhow for internal plumbing

Library Error (thiserror)

use thiserror::Error;

#[derive(Error, Debug)]
pub enum ParseError {
    #[error("invalid syntax at line {line}: {message}")]
    Syntax { line: usize, message: String },

    #[error("unexpected end of file")]
    UnexpectedEof,

    #[error("io error reading input")]
    Io(#[from] std::io::Error),
}

Application Error (anyhow)

use anyhow::{Context, Result, bail, ensure};

fn run() -> Result<()> {
    let config = load_config("app.toml")
        .context("failed to initialize")?;

    ensure!(config.port > 0, "port must be positive, got {}", config.port);

    if config.debug && config.production {
        bail!("cannot enable debug in production");
    }
    Ok(())
}

Error Message Conventions

  • Start lowercase, no trailing punctuation: "invalid input" not "Invalid input."
  • Acronyms and error codes stay uppercase: "DNS lookup failed", "HTTP 503"
  • Context reads naturally when chained: "failed to load config: invalid toml: expected '=' at line 3"

Usage Scenarios

Scenario 1: "I'm writing a library — how should I define errors?" → Use thiserror. Create an enum with one variant per failure mode the caller cares about. Use #[from] for automatic conversion from underlying errors. Don't expose internal error types — wrap them.

Scenario 2: "I have unwrap() calls everywhere in my application" → Replace with ? and anyhow::Result. Add .context() where the error alone isn't enough to diagnose the problem. Keep unwrap() only in tests and for invariants you've already validated.

Scenario 3: "Should I use expect or return an error here?" → If the caller can do something about it (retry, use a default, report to user), return Result. If it means the program's logic is broken (invariant violation), expect("reason this should never fail") is appropriate.


Reference Files

FileRead When
error-patternsSetting up thiserror/anyhow, error chaining, #[from]/#[source], context patterns, documentation
error-decisionsDeciding panic vs Result, designing custom error types, when-to-use-what scenarios, diagnostic crates (miette, color-eyre), user-facing vs internal errors, CLI exit codes

Cross-References

WhenCheck
Error types involving ownership/lifetimesrust-ownership → Quick Decisions
Async error handling patternsrust-async → Quick Decisions
Documenting # Errors sectionsrust-api → Quick Decisions
Clippy lints for error handlingrust-quality → Quick Decisions
Error logging, span tracesrust-tracing → Quick Decisions
Error responses in web handlersrust-architecture → Quick Decisions

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.