error-concept
thiserror: source with operation context
Keep an input identifier and the original parse error together. Create the variant using map_err because conversion needs additional data. Requires thiserror = "=2.0.12" in Cargo.toml. See the staged dependency project. Expected stdout (not executed): row 3: bad quantity; cause=true Expected stderr: (empty) Expected exit: success Common mistake: Replacing the parse error with a plain message loses structured cause information.
Formal Syntax & Structure
rust syntaxrust
#[source] field: EWorking Example
Example Snippetrust
use std::{error::Error, num::ParseIntError};#[derive(Debug, thiserror::Error)]#[error("row {row}: bad quantity")]struct RowError { row: usize, #[source] cause: ParseIntError }fn parse(row: usize, s: &str) -> Result<u32, RowError> { s.parse().map_err(|cause| RowError { row, cause })}fn main() { if let Err(e) = parse(3, "bad") { println!("{e}; cause={}", e.source().is_some()); }}