agentsclimarketplace

Rust errors

Skill dawidpereira/rust-skills/skills/rust-errors

Curated Rust skill files for Claude Code: ownership, async, errors, types, architecture, DDD, and more

Install
npx -y skills add dawidpereira/rust-skills --skill rust-errors

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

One thing to look at

  • 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

What its author says it does

Copied from the file, not written here

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.

SKILL.md

7.9 KB, as published. Nobody here has run it

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

Keep looking

Skills are one crate of 328,083. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.