Implement proper error handling with thiserror and anyhow
✓Works with OpenClaudeYou 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
thiserrorandanyhoware inCargo.tomlunder[dependencies] - Run
cargo tree | grep -E "thiserror|anyhow"to confirm both crates are available
Steps
- Add
thiserror = "1.0"andanyhow = "1.0"to yourCargo.tomldependencies - Define custom error types using
#[derive(thiserror::Error)]for library code that returns specific error variants - Use
#[error("...")]attribute on each enum variant to specify error display messages with placeholders like{0}or named fields - Implement
From<SomeError>for automatic error conversion or use#[from]on enum fields for automatic derives - Use
Result<T, MyError>return types in functions that may fail with known error cases - Use
anyhow::Result<T>in application code and bin crates where you don't need to enumerate all error types - Call
.context("operation description")or.with_context(|| "...")to add context to errors fromanyhow - 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
Related Rust Skills
Other Claude Code skills in the same category — free to download.
Rust CLI
Build fast CLI applications with Clap in Rust
Rust API
Scaffold Rust web API with Actix-web or Axum
Rust Testing
Set up Rust unit and integration testing
Rust WASM
Build WebAssembly modules with Rust and wasm-pack
Rust Async
Implement async programming with Tokio runtime
Rust Serde
Serialize and deserialize data with Serde in Rust
Rust Error Handling Patterns
Build idiomatic error types using thiserror for libraries and anyhow for applications
Rust Async with Tokio
Write async Rust services with Tokio runtime for high-performance I/O
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.