$120 tested Claude codes · real before/after data · Full tier $15 one-timebuy --sheet=15 →
$Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. download --free →
clskills.sh — terminal v2.4 — 2,347 skills indexed● online
[CL]Skills_
RustintermediateNew

Rust Error Handling

Share

Implement proper error handling with thiserror and anyhow

Works with OpenClaude

You are a Rust developer implementing production-grade error handling. The user wants to implement proper error handling using the thiserror and anyhow crates.

What to check first

  • Verify thiserror and anyhow are in Cargo.toml under [dependencies]
  • Run cargo tree | grep -E "thiserror|anyhow" to confirm both crates are available

Steps

  1. Add thiserror = "1.0" and anyhow = "1.0" to your Cargo.toml dependencies
  2. Define custom error types using #[derive(thiserror::Error)] for library code that returns specific error variants
  3. Use #[error("...")] attribute on each enum variant to specify error display messages with placeholders like {0} or named fields
  4. Implement From<SomeError> for automatic error conversion or use #[from] on enum fields for automatic derives
  5. Use Result<T, MyError> return types in functions that may fail with known error cases
  6. Use anyhow::Result<T> in application code and bin crates where you don't need to enumerate all error types
  7. Call .context("operation description") or .with_context(|| "...") to add context to errors from anyhow
  8. Use ? operator to propagate errors up the call stack, letting error type conversions happen automatically

Code

use thiserror::Error;
use anyhow::{Result, Context};
use std::io;
use std::num::ParseIntError;

// Define custom errors for your library
#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("Failed to read config file: {0}")]
    IoError(#[from] io::Error),
    
    #[error("Invalid port number: {0}")]
    ParseError(#[from] ParseIntError),
    
    #[error("Missing required field: {field}")]
    MissingField { field: String },
    
    #[error("Invalid config: {reason}")]
    ValidationError { reason: String },
}

// Library function returning Result with custom error type
pub fn load_config(path: &str) -> Result<Config, ConfigError> {
    let content = std::fs::read_to_string(path)?;
    let port: u16 = content.trim().parse()?;
    
    if port == 0 {
        return Err(ConfigError::ValidationError {
            reason: "port cannot be 0".to_string(),
        });
    }
    
    Ok(Config { port })
}

pub struct Config {
    pub port: u16,
}

// Application code using anyhow for flexibility
pub fn main_app() -> Result<()> {
    let config = load_config("config.txt")
        .context("Failed to load

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

CategoryRust
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
rusterrorsthiserror

Install command:

curl -o ~/.claude/skills/rust-error-handling.md https://claude-skills-hub.vercel.app/skills/rust/rust-error-handling.md

Related Rust Skills

Other Claude Code skills in the same category — free to download.

Want a Rust skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.