error-concept

thiserror: automatic From conversions

Use a variant wrapping an existing error so ? can convert into the surrounding result. This annotation also establishes the causal link. Requires thiserror = "=2.0.12" in Cargo.toml. See the staged dependency project. Expected stdout (not executed): invalid count; cause=true Expected stderr: (empty) Expected exit: success Common mistake: Adding arbitrary context fields to a from variant; construct such variants explicitly.

Formal Syntax & Structure

rust syntaxrust
#[from] source_error

Working Example

Example Snippetrust
use std::{error::Error, num::ParseIntError};#[derive(Debug, thiserror::Error)]enum CountError {    #[error("invalid count")]    Parse(#[from] ParseIntError),}fn count(s: &str) -> Result<u32, CountError> { Ok(s.parse()?) }fn main() {    if let Err(e) = count("oops") {        println!("{e}; cause={}", e.source().is_some());    }}
Rust Reference