error-concept

thiserror: derive typed errors

Give a library caller a concrete error type it can match. The derive supplies Error and the annotated message supplies Display; Debug is derived separately. Requires thiserror = "=2.0.12" in Cargo.toml. See the staged dependency project. Expected stdout (not executed): name exceeds 4 bytes Expected stderr: (empty) Expected exit: success Common mistake: Treating a readable message as the only error contract. Match variants for decisions.

Formal Syntax & Structure

rust syntaxrust
#[derive(Debug, thiserror::Error)]

Working Example

Example Snippetrust
#[derive(Debug, thiserror::Error)]enum NameError {    #[error("name exceeds {limit} bytes")]    TooLong { limit: usize },}fn validate(name: &str) -> Result<(), NameError> {    if name.len() > 4 { return Err(NameError::TooLong { limit: 4 }); }    Ok(())}fn main() {    match validate("Alice") {        Ok(()) => println!("valid"),        Err(e) => println!("{e}"),    }}
Rust Reference