实现说明
核心动作集中在函数 fmt、source、main中。
本示例的循环部分是 while let Some(current) = cause。
使用要点
- 跑完文件,输出里会留下标记——
top:、caused by:。 - 运行整个文件:
main会依次驱动source。
常见问题
运行「沿 source 链下钻到最底层错误」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 top:、caused by: 这类标签。
主要签名是 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
核心语句
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();
代码示例
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();
}
}