Custom error types with thiserror for domain errors

Marcus Chen Jan 2026
1 tab
use thiserror::Error;

#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("file not found: {0}")]
    NotFound(String),

    #[error("parse error at line {line}: {msg}")]
    ParseError { line: usize, msg: String },

    #[error(transparent)]
    Io(#[from] std::io::Error),
}
1 file · rust Explain with highlit

For production code, I define custom error enums using thiserror. It auto-derives Display and Error trait implementations, making errors self-documenting and composable. Each variant can wrap underlying errors (#[from]) for automatic conversion with ?. This gives you typed errors with context rather than generic strings or Box<dyn Error>. I keep one error enum per module or domain, with variants for each failure mode. The #[error("...")] attribute provides user-facing messages with interpolation. When debugging, the full chain is preserved. This pattern scales well: it's zero-cost at runtime, compiler-checked, and far more maintainable than string-based errors. I use it in every Rust library I build.