error-concept

Traverse an error chain

Walk the chain for diagnostic reporting. For custom untrusted error implementations, bound traversal or detect cycles; Error::source does not itself enforce an acyclic chain. Do not expose confidential context to end users. Expected stdout (not executed): levels=2 Common mistake: Reporting only the final message and assuming it explains the failed operation.

Formal Syntax & Structure

rust syntaxrust
while let Some(error) = current { current = error.source(); }

Working Example

Example Snippetrust
use std::{error::Error, fmt, num::ParseIntError};#[derive(Debug)]struct LoadError(ParseIntError);impl fmt::Display for LoadError {    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "invalid inventory quantity") }}impl Error for LoadError {    fn source(&self) -> Option<&(dyn Error + 'static)> { Some(&self.0) }}impl From<ParseIntError> for LoadError {    fn from(e: ParseIntError) -> Self { Self(e) }}fn read_qty(s: &str) -> Result<u32, LoadError> { Ok(s.parse::<u32>()?) }fn main() {    let e = read_qty("bad").unwrap_err();    let mut current: Option<&dyn Error> = Some(&e);    let mut count = 0;    while let Some(error) = current {        count += 1;        if count == 16 { break; }        current = error.source();    }    println!("levels={count}");}
Rust Reference