Day 6:進階錯誤處理三件套整合

學習目標

  • 整合 thiserror + anyhow + tracing
  • 建立 library 與应用各自的錯誤策略
  • 建立完整的錯誤處理範本

今日重點

完整範本:library 層

use thiserror::Error;

#[derive(Error, Debug)]
pub enum StorageError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("serialization error: {0}")]
    Serde(#[from] serde_json::Error),
    #[error("item not found: {0}")]
    NotFound(String),
}

Library 對外提供具體、可 match 的錯誤型別。

完整範本:application 層

use anyhow::{Result, Context};
use tracing::{info, error};

fn load_settings() -> Result<Config> {
    let raw = std::fs::read_to_string("cfg.json")
        .context("read settings")?;
    serde_json::from_str(&raw)
        .context("parse settings")
}

fn main() -> Result<()> {
    tracing_subscriber::fmt().init();
    let cfg = load_settings()?;   // anyhow 統一往上傳
    info!("loaded");
    Ok(())
}

Application 用 anyhow 專注「快速往上傳 + 加可讀上下文」。

分工口訣

Library:thiserror 定義錯誤;Application:anyhow 傳播錯誤; 兩者都可用 tracing 記錄。

練習

將下列「讀檔 → 解析 → 處理」流程設計成 library + application 兩層:

// library: 定義 Config 與 ConfigError(thiserror)
// application: 呼叫並用 anyhow+tracing 輸出
fn main() -> Result<(), anyhow::Error> {
    // 讀設定 -> 解析 -> 印出
    Ok(())
}
1. 設計 library 的 ConfigError 2. application 用 anyhow + context 3. 用 tracing 記錄成功/失敗

自我檢查

  • 能整合三工具建立完整錯誤處理
  • 知道 library 與 application 的分工
  • 會用 tracing 觀察整個流程
  • 建立自己的錯誤處理範本

深入連結

  • Rust 2024 error handling cookbook + thiserror/anyhow 官方範例