std::error::Error Trait
核心概念
std::error::Error 是 Rust 标准库中为错误类型定义的统一接口(trait)。实现了这个 trait 的类型可以融入 Rust 的错误处理生态——可以被 Box<dyn Error> 持有、支持通过 source() 方法追踪错误链、可以和 ? 操作符配合用于返回 Result<T, Box<dyn Error>> 的函数。Error trait 要求类型同时实现 Display 和 Debug,分别提供面向用户和面向开发者的错误描述。
use std::error::Error;
use std::fmt;
// Error trait 的核心定义(简化版)
// pub trait Error: Display + Debug {
// fn source(&self) -> Option<&(dyn Error + 'static)> { None }
// }
#[derive(Debug)]
struct AppError {
message: String,
}
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
// 实现 Error trait(最简形式)
impl Error for AppError {}
fn do_something() -> Result<(), Box<dyn Error>> {
// Box<dyn Error> 可以持有任何实现了 Error 的类型
Err(Box::new(AppError {
message: String::from("出错了"),
}))
}
fn main() {
match do_something() {
Ok(()) => println!("成功"),
Err(e) => {
println!("错误: {}", e); // Display
println!("调试: {:?}", e); // Debug
println!("原因: {:?}", e.source()); // source()
}
}
}Error trait 的方法
use std::error::Error;
use std::fmt;
use std::io;
#[derive(Debug)]
struct ConfigError {
message: String,
source: Option<Box<dyn Error>>, // 可选的底层错误
}
impl ConfigError {
fn new(message: &str) -> Self {
ConfigError {
message: message.to_string(),
source: None,
}
}
fn with_source(message: &str, source: impl Error + 'static) -> Self {
ConfigError {
message: message.to_string(),
source: Some(Box::new(source)),
}
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "配置错误: {}", self.message)
}
}
impl Error for ConfigError {
// source() 返回导致当前错误的底层错误
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref()
}
}
fn load_config() -> Result<String, ConfigError> {
// 读取文件可能失败
let content = std::fs::read_to_string("config.toml")
.map_err(|e| ConfigError::with_source("无法读取配置文件", e))?;
Ok(content)
}
// 打印完整的错误链
fn print_error_chain(err: &dyn Error) {
println!("错误: {}", err);
let mut current = err.source();
while let Some(cause) = current {
println!(" 原因: {}", cause);
current = cause.source();
}
}
fn main() {
match load_config() {
Ok(config) => println!("配置: {}", config),
Err(e) => print_error_chain(&e),
}
}Box<dyn Error> 作为返回类型
Box<dyn Error> 是一种通用错误类型,可以持有任何实现了 Error 的值。适合快速原型开发和 main 函数。
use std::error::Error;
use std::fs;
use std::num::ParseIntError;
// Box<dyn Error> 可以容纳任何错误类型
fn read_number(path: &str) -> Result<i32, Box<dyn Error>> {
let content = fs::read_to_string(path)?; // io::Error → Box<dyn Error>
let number = content.trim().parse::<i32>()?; // ParseIntError → Box<dyn Error>
Ok(number)
}
// main 函数也可以返回 Result
fn main() -> Result<(), Box<dyn Error>> {
// 演示不同错误类型都可以用 ? 传播
let nums = vec!["42", "abc", "100"];
for s in nums {
match s.parse::<i32>() {
Ok(n) => println!("{} → {}", s, n),
Err(e) => println!("{} → 错误: {}", s, e),
}
}
Ok(())
}为枚举错误实现 Error trait
use std::error::Error;
use std::fmt;
use std::io;
use std::num::ParseIntError;
#[derive(Debug)]
enum ServiceError {
Io(io::Error),
Parse(ParseIntError),
Validation(String),
NotFound { resource: String, id: u64 },
}
impl fmt::Display for ServiceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ServiceError::Io(e) => write!(f, "IO 错误: {}", e),
ServiceError::Parse(e) => write!(f, "解析错误: {}", e),
ServiceError::Validation(msg) => write!(f, "验证错误: {}", msg),
ServiceError::NotFound { resource, id } => {
write!(f, "{} #{} 未找到", resource, id)
}
}
}
}
impl Error for ServiceError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
// 返回包装的底层错误
match self {
ServiceError::Io(e) => Some(e),
ServiceError::Parse(e) => Some(e),
ServiceError::Validation(_) => None, // 没有底层错误
ServiceError::NotFound { .. } => None,
}
}
}
impl From<io::Error> for ServiceError {
fn from(e: io::Error) -> Self {
ServiceError::Io(e)
}
}
impl From<ParseIntError> for ServiceError {
fn from(e: ParseIntError) -> Self {
ServiceError::Parse(e)
}
}
fn load_user_age(path: &str) -> Result<u32, ServiceError> {
let content = std::fs::read_to_string(path)?; // io::Error → ServiceError
let age = content.trim().parse::<u32>()?; // ParseIntError → ServiceError
if age > 150 {
return Err(ServiceError::Validation(
format!("年龄 {} 不合理", age)
));
}
Ok(age)
}
fn main() {
match load_user_age("age.txt") {
Ok(age) => println!("年龄: {}", age),
Err(e) => {
println!("错误: {}", e);
if let Some(source) = e.source() {
println!("底层原因: {}", source);
}
}
}
}downcast:恢复具体错误类型
Box<dyn Error> 可以通过 downcast_ref 恢复为具体的错误类型。
use std::error::Error;
use std::fmt;
#[derive(Debug)]
struct NotFoundError {
resource: String,
}
#[derive(Debug)]
struct PermissionError {
action: String,
}
impl fmt::Display for NotFoundError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} 未找到", self.resource)
}
}
impl fmt::Display for PermissionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "无权执行: {}", self.action)
}
}
impl Error for NotFoundError {}
impl Error for PermissionError {}
fn simulate_error(code: u32) -> Result<(), Box<dyn Error>> {
match code {
404 => Err(Box::new(NotFoundError {
resource: String::from("用户"),
})),
403 => Err(Box::new(PermissionError {
action: String::from("删除"),
})),
_ => Ok(()),
}
}
fn handle_error(err: &Box<dyn Error>) {
// 尝试 downcast 到具体类型
if let Some(e) = err.downcast_ref::<NotFoundError>() {
println!("处理 NotFound: {} 不存在", e.resource);
} else if let Some(e) = err.downcast_ref::<PermissionError>() {
println!("处理 Permission: 无权 {}", e.action);
} else {
println!("未知错误: {}", err);
}
}
fn main() {
for code in &[200, 404, 403] {
match simulate_error(*code) {
Ok(()) => println!("状态 {}: 成功", code),
Err(e) => {
print!("状态 {}: ", code);
handle_error(&e);
}
}
}
}自定义错误 vs Box<dyn Error>
| 特性 | 自定义枚举错误 | Box<dyn Error> |
|---|---|---|
| 类型安全 | 编译时确定所有变体 | 运行时才知道类型 |
| match 处理 | 可以穷尽匹配 | 需要 downcast |
| 代码量 | 多(需要定义和实现) | 少 |
| 适用场景 | 库 API、生产代码 | 快速原型、main 函数 |
| 性能 | 栈分配(通常) | 堆分配 |
| 错误信息 | 精确的变体数据 | 通用 Display 消息 |
基本示例
构建一个带完整错误链追踪的文件处理系统:
use std::error::Error;
use std::fmt;
use std::io;
use std::num::ParseFloatError;
// 解析错误
#[derive(Debug)]
struct ParseError {
line: usize,
content: String,
source: ParseFloatError,
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "第{}行解析失败: '{}'", self.line, self.content)
}
}
impl Error for ParseError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.source)
}
}
// 处理错误
#[derive(Debug)]
enum ProcessError {
FileRead { path: String, source: io::Error },
DataParse(ParseError),
EmptyData,
Computation(String),
}
impl fmt::Display for ProcessError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ProcessError::FileRead { path, .. } => {
write!(f, "读取文件 '{}' 失败", path)
}
ProcessError::DataParse(e) => write!(f, "数据解析失败: {}", e),
ProcessError::EmptyData => write!(f, "没有有效数据"),
ProcessError::Computation(msg) => write!(f, "计算错误: {}", msg),
}
}
}
impl Error for ProcessError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ProcessError::FileRead { source, .. } => Some(source),
ProcessError::DataParse(e) => Some(e),
ProcessError::EmptyData => None,
ProcessError::Computation(_) => None,
}
}
}
impl From<ParseError> for ProcessError {
fn from(e: ParseError) -> Self {
ProcessError::DataParse(e)
}
}
// 解析数据行
fn parse_values(content: &str) -> Result<Vec<f64>, ParseError> {
let mut values = Vec::new();
for (i, line) in content.lines().enumerate() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
let value = trimmed.parse::<f64>().map_err(|e| ParseError {
line: i + 1,
content: trimmed.to_string(),
source: e,
})?;
values.push(value);
}
Ok(values)
}
// 处理文件
fn process_data(path: &str) -> Result<String, ProcessError> {
let content = std::fs::read_to_string(path)
.map_err(|e| ProcessError::FileRead {
path: path.to_string(),
source: e,
})?;
let values = parse_values(&content)?; // ParseError → ProcessError
if values.is_empty() {
return Err(ProcessError::EmptyData);
}
let sum: f64 = values.iter().sum();
let mean = sum / values.len() as f64;
let min = values.iter().cloned().reduce(f64::min).unwrap();
let max = values.iter().cloned().reduce(f64::max).unwrap();
Ok(format!(
"数量={}, 均值={:.2}, 最小={:.2}, 最大={:.2}",
values.len(), mean, min, max
))
}
// 打印完整错误链
fn print_full_error(err: &dyn Error) {
eprintln!("错误: {}", err);
let mut depth = 0;
let mut current = err.source();
while let Some(cause) = current {
depth += 1;
eprintln!("{}原因 {}: {}", " ".repeat(depth), depth, cause);
current = cause.source();
}
}
fn main() {
// 尝试处理文件
match process_data("numbers.txt") {
Ok(report) => println!("结果: {}", report),
Err(e) => print_full_error(&e),
}
// 手动测试解析错误链
println!("\n--- 错误链演示 ---");
let test_data = "10.5\nabc\n20.0";
match parse_values(test_data) {
Ok(v) => println!("解析成功: {:?}", v),
Err(e) => {
let process_err = ProcessError::from(e);
print_full_error(&process_err);
// 输出:
// 错误: 数据解析失败: 第2行解析失败: 'abc'
// 原因 1: 第2行解析失败: 'abc'
// 原因 2: invalid float literal
}
}
}常见问题
问题一:什么时候用 Box<dyn Error>,什么时候用自定义错误?
快速原型、示例代码、main 函数用 Box<dyn Error>。库 API、生产代码用自定义错误类型。自定义类型让调用者可以精确 match 不同错误。
问题二:source() 方法有什么用?
source() 返回导致当前错误的底层错误,形成错误链。调试时可以沿着错误链追踪到根本原因。日志系统可以自动记录完整的错误链。
问题三:Error trait 必须实现吗?
不是强制的,但强烈推荐。不实现 Error 的错误类型无法与 Box<dyn Error> 配合,也无法参与错误链。标准库的 io::Error、ParseIntError 等都实现了 Error。
问题四:为什么 Error trait 要求 Display + Debug?
Display 提供面向用户的可读消息(如"文件不存在"),Debug 提供面向开发者的详细信息(如内部字段值)。两者缺一不可:用户需要可读消息,开发者需要调试细节。
适用场景
- 库开发:为公开 API 的错误类型实现 Error trait
- 错误链追踪:通过 source() 追踪根本原因
- 通用错误处理:Box<dyn Error> 作为万能错误类型
- 日志记录:自动记录完整的错误上下文
注意事项
Errortrait 要求同时实现Display和Debugsource()默认返回None,需要手动实现以返回底层错误Box<dyn Error>方便但失去了编译时类型信息- 实现
Fromtrait 配合?操作符实现自动转换 downcast_ref可以从dyn Error恢复具体类型- 错误链中每层的
source()应该指向直接原因
总结
std::error::Error 是 Rust 错误处理生态的统一接口,要求错误类型同时实现 Display(用户友好消息)和 Debug(开发者调试信息)。核心方法 source() 用于返回导致当前错误的底层错误,形成可追踪的错误链。Box<dyn Error> 作为通用错误类型可以持有任何实现了 Error 的值,适合快速开发和 main 函数,但库 API 推荐使用自定义枚举错误以保留编译时类型安全。通过 downcast_ref 可以从动态错误恢复为具体类型。实现 Error trait 配合 From trait 和 ? 操作符,构成了 Rust 完整的错误传播机制。