跳至主要內容
rust 随笔(三)

Rust 随笔(三)

thiserror

这篇文章探讨一个常见的错误处理库——thiserror 首先我们回顾一下上一篇的Error第二种用法:

#[derive(Debug)]
pub enum AppError {
    Config(ConfigError),
    Database(DatabaseError),
    Query(QueryError),
    Io(io::Error), // 有时也可能直接暴露一些通用的 IO 错误
    Initialization(String), // 其他初始化错误
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AppError::Config(err) => write!(f, "{}", err), // 直接调用 ConfigError 的 Display
            AppError::Database(err) => write!(f, "{}", err), // 直接调用 DatabaseError 的 Display
            AppError::Query(err) => write!(f, "{}", err),
            AppError::Io(err) => write!(f, "IO 错误: {}", err),
            AppError::Initialization(msg) => write!(f, "初始化错误: {}", msg),
        }
    }
}

impl Error for AppError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            AppError::Config(err) => Some(err),    // ConfigError 实现了 Error,可以作为 source
            AppError::Database(err) => Some(err),  // DatabaseError 实现了 Error
            AppError::Query(err) => Some(err),     // QueryError 实现了 Error
            AppError::Io(err) => Some(err),        // io::Error 本身就实现了 Error
            AppError::Initialization(_) => None,
        }
    }
}

// 实现 From trait
impl From<ConfigError> for AppError {
    fn from(err: ConfigError) -> Self {
        AppError::Config(err)
    }
}

impl From<DatabaseError> for AppError {
    fn from(err: DatabaseError) -> Self {
        AppError::Database(err)
    }
}

impl From<QueryError> for AppError {
    fn from(err: QueryError) -> Self {
        AppError::Query(err)
    }
}

impl From<io::Error> for AppError { // 有时也希望直接转换IO错误
    fn from(err: io::Error) -> Self {
        AppError::Io(err)
    }
}

Mr.Lexon大约 4 分钟rustrustthiserror