Walk Error Source Chains Down To The Root
Loop over Error::source to print every layer of a failure, ending at the deepest cause so logs keep both the user-facing message and the parser error.
Code
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
struct RowError {
row: usize,
source: ParseIntError,
}
impl fmt::Display for RowError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "row {} is not a valid count", self.row)
}
}
impl Error for RowError {
// source 指向内层原因:这里是解析失败本身
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.source)
}
}
fn main() {
let source: ParseIntError = "twelve".parse::<u32>().unwrap_err();
let err = RowError { row: 7, source };
// 逐层下钻:顶层是人话,最里层是机器原因;循环在 source 返回 None 时终止
println!("top: {err}");
let mut cause: Option<&(dyn Error + 'static)> = err.source();
while let Some(current) = cause {
println!("caused by: {current}");
cause = current.source();
}
}Inside the snippet
Walk Error Source Chains Down To The Root reduces to the functions fmt, source and main.
Repetition is confined to while let Some(current) = cause — the rest of the file is straight-line.
Putting it to use
The main signature reads fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
Running the file prints labeled results such as top:, caused by: — each operation’s effect is visible in the output.
Execute the file and main walks through source, in that order.
Core lines
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.source)
}
while let Some(current) = cause {
println!("caused by: {current}");
cause = current.source();
}
let source: ParseIntError = "twelve".parse::<u32>().unwrap_err();
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.SPDX License LookupSearch common SPDX license identifiers and see permissions, conditions, limitations, copyleft strength, and OSI or FSF approval status.
FAQ
- What does Walk Error Source Chains Down To The Root print when run?
- Running the file directly is enough — expect labeled output lines such as `top:`, `caused by:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.