自定义错误类型 ​

核心概念 ​

在实际项目中,标准库或第三方库的错误类型往往无法完整描述你的业务错误。自定义错误类型让你可以用枚举精确表达所有可能的失败情况,每个变体携带相应的上下文数据。Rust 中自定义错误类型通常是一个枚举,需要实现 std::fmt::Display 和 std::fmt::Debug trait,还推荐实现 std::error::Error trait 以融入 Rust 的错误处理生态。

rust
use std::fmt;

// 自定义错误类型:用枚举列出所有可能的错误
#[derive(Debug)]
enum AuthError {
    UserNotFound(String),
    WrongPassword,
    AccountLocked { username: String, until: String },
    TokenExpired,
}

// 实现 Display:提供给终端用户看的友好消息
impl fmt::Display for AuthError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AuthError::UserNotFound(name) => write!(f, "用户 '{}' 不存在", name),
            AuthError::WrongPassword => write!(f, "密码错误"),
            AuthError::AccountLocked { username, until } => {
                write!(f, "账户 '{}' 已锁定,解锁时间: {}", username, until)
            }
            AuthError::TokenExpired => write!(f, "登录令牌已过期"),
        }
    }
}

fn login(username: &str, password: &str) -> Result<String, AuthError> {
    if username == "locked_user" {
        return Err(AuthError::AccountLocked {
            username: username.to_string(),
            until: String::from("2026-12-31"),
        });
    }
    if username != "admin" {
        return Err(AuthError::UserNotFound(username.to_string()));
    }
    if password != "123456" {
        return Err(AuthError::WrongPassword);
    }
    Ok(String::from("token_abc123"))
}

fn main() {
    let attempts = vec![
        ("admin", "123456"),
        ("admin", "wrong"),
        ("nobody", "123"),
        ("locked_user", "123"),
    ];

    for (user, pass) in attempts {
        match login(user, pass) {
            Ok(token) => println!("登录成功: {}", token),
            Err(e) => println!("登录失败: {}", e),
        }
    }
}

错误类型的设计原则 ​

用枚举表示不同的错误类别 ​

rust
use std::fmt;

#[derive(Debug)]
enum DatabaseError {
    // 连接相关
    ConnectionFailed(String),
    ConnectionTimeout { host: String, timeout_ms: u64 },

    // 查询相关
    QuerySyntaxError(String),
    RecordNotFound { table: String, id: u64 },
    DuplicateKey { table: String, key: String },

    // 数据相关
    InvalidData { field: String, reason: String },
    ConstraintViolation(String),
}

impl fmt::Display for DatabaseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DatabaseError::ConnectionFailed(msg) => {
                write!(f, "数据库连接失败: {}", msg)
            }
            DatabaseError::ConnectionTimeout { host, timeout_ms } => {
                write!(f, "连接 {} 超时 ({}ms)", host, timeout_ms)
            }
            DatabaseError::QuerySyntaxError(sql) => {
                write!(f, "SQL 语法错误: {}", sql)
            }
            DatabaseError::RecordNotFound { table, id } => {
                write!(f, "表 {} 中未找到记录 #{}", table, id)
            }
            DatabaseError::DuplicateKey { table, key } => {
                write!(f, "表 {} 中键 '{}' 已存在", table, key)
            }
            DatabaseError::InvalidData { field, reason } => {
                write!(f, "字段 '{}' 数据无效: {}", field, reason)
            }
            DatabaseError::ConstraintViolation(msg) => {
                write!(f, "约束违反: {}", msg)
            }
        }
    }
}

fn insert_user(name: &str, email: &str) -> Result<u64, DatabaseError> {
    if name.is_empty() {
        return Err(DatabaseError::InvalidData {
            field: String::from("name"),
            reason: String::from("不能为空"),
        });
    }
    if !email.contains('@') {
        return Err(DatabaseError::InvalidData {
            field: String::from("email"),
            reason: format!("'{}' 格式无效", email),
        });
    }
    if name == "admin" {
        return Err(DatabaseError::DuplicateKey {
            table: String::from("users"),
            key: name.to_string(),
        });
    }
    // 模拟成功插入
    Ok(42)
}

fn main() {
    let cases = vec![
        ("张三", "zhangsan@test.com"),
        ("", "empty@test.com"),
        ("李四", "invalid"),
        ("admin", "admin@test.com"),
    ];

    for (name, email) in cases {
        match insert_user(name, email) {
            Ok(id) => println!("插入成功: id={}", id),
            Err(e) => println!("插入失败: {}", e),
        }
    }
}

用结构体表示单一错误 ​

当错误类型只有一种,不需要区分类别时,可以用结构体。

rust
use std::fmt;

#[derive(Debug)]
struct ValidationError {
    field: String,
    message: String,
}

impl ValidationError {
    fn new(field: &str, message: &str) -> Self {
        ValidationError {
            field: field.to_string(),
            message: message.to_string(),
        }
    }
}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "字段 '{}' 验证失败: {}", self.field, self.message)
    }
}

fn validate_age(age: i32) -> Result<u32, ValidationError> {
    if age < 0 {
        return Err(ValidationError::new("age", "不能为负数"));
    }
    if age > 150 {
        return Err(ValidationError::new("age", "不能大于 150"));
    }
    Ok(age as u32)
}

fn main() {
    for age in &[25, -5, 200] {
        match validate_age(*age) {
            Ok(a) => println!("年龄有效: {}", a),
            Err(e) => println!("{}", e),
        }
    }
}

包装底层错误 ​

自定义错误通常需要包含底层错误作为"原因"。

rust
use std::fmt;
use std::io;
use std::num::ParseIntError;

#[derive(Debug)]
enum AppError {
    Io(io::Error),
    Parse(ParseIntError),
    Config(String),
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AppError::Io(e) => write!(f, "IO 错误: {}", e),
            AppError::Parse(e) => write!(f, "解析错误: {}", e),
            AppError::Config(msg) => write!(f, "配置错误: {}", msg),
        }
    }
}

// 实现 From trait 支持 ? 操作符自动转换
impl From<io::Error> for AppError {
    fn from(e: io::Error) -> Self {
        AppError::Io(e)
    }
}

impl From<ParseIntError> for AppError {
    fn from(e: ParseIntError) -> Self {
        AppError::Parse(e)
    }
}

fn load_config(path: &str) -> Result<u16, AppError> {
    // ? 自动将 io::Error 转为 AppError::Io
    let content = std::fs::read_to_string(path)?;

    // ? 自动将 ParseIntError 转为 AppError::Parse
    let port = content.trim().parse::<u16>()?;

    if port == 0 {
        return Err(AppError::Config(String::from("端口不能为 0")));
    }

    Ok(port)
}

fn main() {
    match load_config("port.txt") {
        Ok(port) => println!("端口: {}", port),
        Err(e) => {
            println!("加载失败: {}", e);
            // Debug 格式查看内部细节
            println!("详细: {:?}", e);
        }
    }
}

多层错误包装 ​

rust
use std::fmt;
use std::collections::HashMap;

// 底层:数据存储错误
#[derive(Debug)]
enum StorageError {
    NotFound(String),
    PermissionDenied,
}

impl fmt::Display for StorageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StorageError::NotFound(key) => write!(f, "键 '{}' 不存在", key),
            StorageError::PermissionDenied => write!(f, "权限不足"),
        }
    }
}

// 中间层:服务错误(包装底层错误)
#[derive(Debug)]
enum ServiceError {
    Storage(StorageError),         // 包装存储错误
    Validation(String),            // 自身的验证错误
    BusinessRule(String),          // 业务规则错误
}

impl fmt::Display for ServiceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ServiceError::Storage(e) => write!(f, "存储层: {}", e),
            ServiceError::Validation(msg) => write!(f, "验证: {}", msg),
            ServiceError::BusinessRule(msg) => write!(f, "业务: {}", msg),
        }
    }
}

impl From<StorageError> for ServiceError {
    fn from(e: StorageError) -> Self {
        ServiceError::Storage(e)
    }
}

// 模拟存储层
struct Storage {
    data: HashMap<String, String>,
}

impl Storage {
    fn new() -> Self {
        let mut data = HashMap::new();
        data.insert(String::from("user:1"), String::from("张三"));
        data.insert(String::from("user:2"), String::from("李四"));
        Storage { data }
    }

    fn get(&self, key: &str) -> Result<&String, StorageError> {
        self.data.get(key).ok_or_else(|| StorageError::NotFound(key.to_string()))
    }

    fn set(&mut self, key: &str, value: &str) -> Result<(), StorageError> {
        self.data.insert(key.to_string(), value.to_string());
        Ok(())
    }
}

// 服务层
struct UserService {
    storage: Storage,
}

impl UserService {
    fn new() -> Self {
        UserService { storage: Storage::new() }
    }

    fn get_user(&self, id: u32) -> Result<String, ServiceError> {
        let key = format!("user:{}", id);
        // ? 自动将 StorageError 转为 ServiceError::Storage
        let name = self.storage.get(&key)?;
        Ok(name.clone())
    }

    fn rename_user(&mut self, id: u32, new_name: &str) -> Result<(), ServiceError> {
        if new_name.is_empty() {
            return Err(ServiceError::Validation(String::from("名字不能为空")));
        }
        if new_name.len() > 50 {
            return Err(ServiceError::Validation(String::from("名字不能超过 50 字符")));
        }

        // 先检查用户是否存在
        let key = format!("user:{}", id);
        self.storage.get(&key)?;

        // 业务规则检查
        if new_name == "admin" {
            return Err(ServiceError::BusinessRule(
                String::from("不能使用保留名称 'admin'")
            ));
        }

        self.storage.set(&key, new_name)?;
        Ok(())
    }
}

fn main() {
    let mut service = UserService::new();

    // 查询存在的用户
    match service.get_user(1) {
        Ok(name) => println!("用户1: {}", name),
        Err(e) => println!("错误: {}", e),
    }

    // 查询不存在的用户
    match service.get_user(99) {
        Ok(name) => println!("用户99: {}", name),
        Err(e) => println!("错误: {}", e),
    }

    // 重命名
    match service.rename_user(1, "王五") {
        Ok(()) => println!("重命名成功"),
        Err(e) => println!("错误: {}", e),
    }

    // 空名字
    match service.rename_user(1, "") {
        Ok(()) => println!("重命名成功"),
        Err(e) => println!("错误: {}", e),
    }

    // 保留名称
    match service.rename_user(1, "admin") {
        Ok(()) => println!("重命名成功"),
        Err(e) => println!("错误: {}", e),
    }
}

基本示例 ​

设计一个完整的文件处理器错误体系:

rust
use std::fmt;
use std::io;
use std::num::ParseFloatError;

// 完整的错误类型:涵盖所有可能的失败
#[derive(Debug)]
enum FileProcessError {
    // 文件操作错误(包装 io::Error)
    ReadError { path: String, source: io::Error },
    WriteError { path: String, source: io::Error },

    // 数据格式错误
    EmptyFile(String),
    InvalidFormat { line: usize, content: String },
    ParseNumber { line: usize, value: String, source: ParseFloatError },

    // 业务逻辑错误
    NoData,
    InvalidRange { min: f64, max: f64 },
}

impl fmt::Display for FileProcessError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FileProcessError::ReadError { path, source } => {
                write!(f, "读取 '{}' 失败: {}", path, source)
            }
            FileProcessError::WriteError { path, source } => {
                write!(f, "写入 '{}' 失败: {}", path, source)
            }
            FileProcessError::EmptyFile(path) => {
                write!(f, "文件 '{}' 为空", path)
            }
            FileProcessError::InvalidFormat { line, content } => {
                write!(f, "第{}行格式无效: '{}'", line, content)
            }
            FileProcessError::ParseNumber { line, value, source } => {
                write!(f, "第{}行 '{}' 不是有效数字: {}", line, value, source)
            }
            FileProcessError::NoData => write!(f, "没有有效数据"),
            FileProcessError::InvalidRange { min, max } => {
                write!(f, "无效范围: 最小值 {} 大于最大值 {}", min, max)
            }
        }
    }
}

// 读取并解析数据文件
fn read_data_file(path: &str) -> Result<Vec<f64>, FileProcessError> {
    let content = std::fs::read_to_string(path)
        .map_err(|e| FileProcessError::ReadError {
            path: path.to_string(),
            source: e,
        })?;

    if content.trim().is_empty() {
        return Err(FileProcessError::EmptyFile(path.to_string()));
    }

    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| {
            FileProcessError::ParseNumber {
                line: i + 1,
                value: trimmed.to_string(),
                source: e,
            }
        })?;

        values.push(value);
    }

    if values.is_empty() {
        return Err(FileProcessError::NoData);
    }

    Ok(values)
}

// 统计分析
fn analyze(values: &[f64]) -> Result<String, FileProcessError> {
    if values.is_empty() {
        return Err(FileProcessError::NoData);
    }

    let sum: f64 = values.iter().sum();
    let count = values.len();
    let mean = sum / count as f64;

    let min = values.iter().cloned().reduce(f64::min).unwrap();
    let max = values.iter().cloned().reduce(f64::max).unwrap();

    let variance: f64 = values.iter()
        .map(|v| (v - mean).powi(2))
        .sum::<f64>() / count as f64;
    let std_dev = variance.sqrt();

    Ok(format!(
        "数据量: {}\n平均值: {:.2}\n最小值: {:.2}\n最大值: {:.2}\n标准差: {:.2}",
        count, mean, min, max, std_dev
    ))
}

// 写入结果
fn write_report(path: &str, report: &str) -> Result<(), FileProcessError> {
    std::fs::write(path, report).map_err(|e| FileProcessError::WriteError {
        path: path.to_string(),
        source: e,
    })
}

fn process_file(input: &str, output: &str) -> Result<(), FileProcessError> {
    let values = read_data_file(input)?;
    let report = analyze(&values)?;
    println!("{}", report);
    write_report(output, &report)?;
    Ok(())
}

fn main() {
    // 模拟处理(文件不存在会触发 ReadError)
    match process_file("data.txt", "report.txt") {
        Ok(()) => println!("处理完成"),
        Err(e) => {
            println!("处理失败: {}", e);
            // 根据错误类型做不同处理
            match &e {
                FileProcessError::ReadError { path, .. } => {
                    println!("  建议: 检查文件 '{}' 是否存在", path);
                }
                FileProcessError::ParseNumber { line, value, .. } => {
                    println!("  建议: 修正第{}行的值 '{}'", line, value);
                }
                _ => {
                    println!("  详细: {:?}", e);
                }
            }
        }
    }
}

常见问题 ​

问题一:错误类型用枚举还是结构体?

场景选择原因
多种不同类别的错误枚举每个变体表示一种错误类别
只有一种错误结构体简单直接
需要 match 分类处理枚举模式匹配友好
只需要错误消息String 或结构体不需要分类

问题二:Display 和 Debug 的区别?

Display({})给用户看,消息应该友好可读。Debug({:?})给开发者看,应该包含内部细节。derive(Debug) 自动生成,Display 必须手动实现。

问题三:什么时候需要实现 std::error::Error trait?

当你的错误类型需要融入 Rust 错误处理生态(比如和 Box<dyn Error> 配合)、需要 source() 方法追踪错误链时,应该实现 Error trait。下一节会详细介绍。

问题四:为什么要用 From trait?

实现 From<OtherError> for MyError 后,? 操作符可以自动将 OtherError 转换为 MyError,不需要每次手写 map_err。

适用场景 ​

  • 应用程序:定义应用级别的统一错误类型
  • 库开发:提供明确的公开错误类型
  • 多层架构:每层定义自己的错误类型并包装下层错误
  • API 设计:给调用者提供可 match 的错误分类

注意事项 ​

  • 枚举错误类型应该列出所有可能的错误类别
  • 必须实现 Display(给用户看)和 Debug(给开发者看)
  • 建议实现 std::error::Error trait
  • 用 From trait 支持 ? 操作符自动转换
  • 变体中携带足够的上下文数据帮助排查问题
  • 保持错误类型的粒度适中,太粗无法区分,太细难以维护

总结 ​

自定义错误类型是 Rust 中组织业务错误的标准方式。通常用枚举定义,每个变体表示一种错误类别并携带相关的上下文数据。必须实现 Display(面向用户的友好消息)和 Debug(面向开发者的详细信息)。通过实现 From trait 可以让 ? 操作符自动转换底层错误。在多层架构中,每层定义自己的错误类型并包装下层错误,形成清晰的错误传播链。错误类型的设计应该在粒度上找到平衡——足够细以便调用者区分和处理,又不至于太细增加维护负担。