当前位置: 代码网 > it编程>编程语言>rust > 浅谈Rust中错误处理与响应构建

浅谈Rust中错误处理与响应构建

2026年01月08日 rust 我要评论
rust作为一门系统编程语言,以其内存安全和零成本抽象而闻名。在错误处理方面,rust采用了独特而强大的机制,摒弃了传统的异常处理方式,转而使用类型系统来强制开发者显式地处理错误。本文将深入探讨rus

rust作为一门系统编程语言,以其内存安全和零成本抽象而闻名。在错误处理方面,rust采用了独特而强大的机制,摒弃了传统的异常处理方式,转而使用类型系统来强制开发者显式地处理错误。本文将深入探讨rust中的错误处理机制、最佳实践以及如何构建健壮的错误响应系统。

第一部分:rust错误处理基础

1.1 result类型:错误处理的核心

在rust中,result<t, e>是错误处理的基石。它是一个枚举类型,定义如下:

enum result<t, e> {
    ok(t),
    err(e),
}

这个设计迫使开发者必须处理可能出现的错误,编译器会检查是否所有的错误情况都得到了处理。

基本使用示例:

use std::fs::file;
use std::io::read;

fn read_file_content(path: &str) -> result<string, std::io::error> {
    let mut file = file::open(path)?;
    let mut content = string::new();
    file.read_to_string(&mut content)?;
    ok(content)
}

fn main() {
    match read_file_content("example.txt") {
        ok(content) => println!("文件内容: {}", content),
        err(e) => eprintln!("读取文件错误: {}", e),
    }
}

1.2 option类型:处理可能不存在的值

option<t>用于表示值可能存在也可能不存在的情况:

enum option<t> {
    some(t),
    none,
}

实际应用场景:

fn find_user_by_id(id: u32, users: &vec<user>) -> option<&user> {
    users.iter().find(|user| user.id == id)
}

fn get_user_email(id: u32, users: &vec<user>) -> option<string> {
    find_user_by_id(id, users)
        .and_then(|user| user.email.clone())
}

1.3 ?操作符:简化错误传播

?操作符是rust中最优雅的错误处理特性之一。它会自动进行错误传播,如果遇到错误就提前返回。

fn process_data() -> result<(), box<dyn std::error::error>> {
    let data = fetch_data()?;
    let parsed = parse_data(&data)?;
    let validated = validate_data(parsed)?;
    save_data(validated)?;
    ok(())
}

第二部分:自定义错误类型

2.1 实现std::error::error trait

创建自定义错误类型需要实现std::error::error trait:

use std::fmt;
use std::error::error;

#[derive(debug)]
enum databaseerror {
    connectionfailed(string),
    queryfailed(string),
    datanotfound(string),
    invaliddata(string),
}

impl fmt::display for databaseerror {
    fn fmt(&self, f: &mut fmt::formatter) -> fmt::result {
        match self {
            databaseerror::connectionfailed(msg) => 
                write!(f, "数据库连接失败: {}", msg),
            databaseerror::queryfailed(msg) => 
                write!(f, "查询执行失败: {}", msg),
            databaseerror::datanotfound(msg) => 
                write!(f, "数据未找到: {}", msg),
            databaseerror::invaliddata(msg) => 
                write!(f, "数据格式无效: {}", msg),
        }
    }
}

impl error for databaseerror {}

2.2 使用thiserror库简化错误定义

thiserror是一个流行的库,可以大幅简化错误类型的定义:

use thiserror::error;

#[derive(error, debug)]
pub enum apperror {
    #[error("数据库错误: {0}")]
    database(#[from] sqlx::error),
    
    #[error("io错误: {0}")]
    io(#[from] std::io::error),
    
    #[error("序列化错误: {0}")]
    serialization(#[from] serde_json::error),
    
    #[error("验证失败: {field} - {message}")]
    validation {
        field: string,
        message: string,
    },
    
    #[error("未授权访问")]
    unauthorized,
    
    #[error("资源未找到: {0}")]
    notfound(string),
}

2.3 错误上下文与错误链

使用anyhow库可以轻松添加错误上下文:

use anyhow::{context, result};

fn load_config() -> result<config> {
    let content = std::fs::read_to_string("config.toml")
        .context("无法读取配置文件 config.toml")?;
    
    let config: config = toml::from_str(&content)
        .context("配置文件格式错误")?;
    
    ok(config)
}

fn initialize_app() -> result<app> {
    let config = load_config()
        .context("应用初始化失败")?;
    
    let database = connect_database(&config.database_url)
        .context("数据库连接失败")?;
    
    ok(app { config, database })
}

第三部分:web应用中的错误处理

3.1 actix-web框架的错误处理

在actix-web中,错误处理需要实现responseerror trait:

use actix_web::{error, http::statuscode, httpresponse};
use serde::serialize;

#[derive(debug, serialize)]
struct errorresponse {
    code: string,
    message: string,
    details: option<vec<string>>,
}

impl error::responseerror for apperror {
    fn error_response(&self) -> httpresponse {
        let (status, code, message) = match self {
            apperror::database(_) => (
                statuscode::internal_server_error,
                "database_error",
                "数据库操作失败",
            ),
            apperror::validation { field, message } => (
                statuscode::bad_request,
                "validation_error",
                message.as_str(),
            ),
            apperror::unauthorized => (
                statuscode::unauthorized,
                "unauthorized",
                "未授权访问",
            ),
            apperror::notfound(resource) => (
                statuscode::not_found,
                "not_found",
                &format!("资源未找到: {}", resource),
            ),
            _ => (
                statuscode::internal_server_error,
                "internal_error",
                "服务器内部错误",
            ),
        };

        httpresponse::build(status).json(errorresponse {
            code: code.to_string(),
            message: message.to_string(),
            details: none,
        })
    }

    fn status_code(&self) -> statuscode {
        match self {
            apperror::validation { .. } => statuscode::bad_request,
            apperror::unauthorized => statuscode::unauthorized,
            apperror::notfound(_) => statuscode::not_found,
            _ => statuscode::internal_server_error,
        }
    }
}

3.2 中间件层的错误处理

实现全局错误处理中间件:

use actix_web::{
    dev::{servicerequest, serviceresponse},
    middleware::{errorhandlerresponse, errorhandlers},
    result,
};

fn error_handler<b>(
    res: serviceresponse<b>,
) -> result<errorhandlerresponse<b>> {
    let status = res.status();
    
    // 记录错误日志
    if status.is_server_error() {
        log::error!("服务器错误: {} - {:?}", status, res.request().path());
    } else if status.is_client_error() {
        log::warn!("客户端错误: {} - {:?}", status, res.request().path());
    }
    
    ok(errorhandlerresponse::response(res.map_into_left_body()))
}

// 在app中注册
app::new()
    .wrap(
        errorhandlers::new()
            .handler(statuscode::internal_server_error, error_handler)
            .handler(statuscode::bad_request, error_handler)
            .handler(statuscode::not_found, error_handler)
    )

3.3 restful api的错误响应设计

设计统一的api错误响应格式:

#[derive(serialize, debug)]
struct apiresponse<t> {
    success: bool,
    data: option<t>,
    error: option<apierror>,
    timestamp: i64,
}

#[derive(serialize, debug)]
struct apierror {
    code: string,
    message: string,
    details: option<serde_json::value>,
    trace_id: option<string>,
}

impl<t: serialize> apiresponse<t> {
    fn success(data: t) -> self {
        self {
            success: true,
            data: some(data),
            error: none,
            timestamp: chrono::utc::now().timestamp(),
        }
    }
    
    fn error(code: &str, message: &str) -> apiresponse<()> {
        apiresponse {
            success: false,
            data: none,
            error: some(apierror {
                code: code.to_string(),
                message: message.to_string(),
                details: none,
                trace_id: some(uuid::uuid::new_v4().to_string()),
            }),
            timestamp: chrono::utc::now().timestamp(),
        }
    }
}

// 使用示例
async fn get_user(id: web::path<u32>) -> result<httpresponse, apperror> {
    let user = fetch_user(*id).await?;
    ok(httpresponse::ok().json(apiresponse::success(user)))
}

第四部分:高级错误处理模式

4.1 result类型的组合器

rust提供了丰富的组合器方法来处理result:

fn process_user_data(user_id: u32) -> result<processeddata, apperror> {
    // map: 转换ok值
    let user = get_user(user_id)
        .map(|u| user {
            name: u.name.to_uppercase(),
            ..u
        })?;
    
    // and_then: 链式调用返回result的函数
    let profile = get_user_profile(user_id)
        .and_then(|p| validate_profile(p))?;
    
    // or_else: 处理错误情况
    let settings = get_user_settings(user_id)
        .or_else(|_| ok(usersettings::default()))?;
    
    // map_err: 转换错误类型
    let preferences = load_preferences(user_id)
        .map_err(|e| apperror::database(e.into()))?;
    
    ok(processeddata {
        user,
        profile,
        settings,
        preferences,
    })
}

4.2 提前返回与错误恢复

实现优雅的错误恢复策略:

async fn fetch_data_with_fallback(id: u32) -> result<data, apperror> {
    // 尝试从主数据源获取
    match fetch_from_primary(id).await {
        ok(data) => return ok(data),
        err(e) => {
            log::warn!("主数据源失败: {}, 尝试备用源", e);
        }
    }
    
    // 尝试从缓存获取
    match fetch_from_cache(id).await {
        ok(data) => {
            log::info!("从缓存获取数据成功");
            return ok(data);
        }
        err(e) => {
            log::warn!("缓存获取失败: {}", e);
        }
    }
    
    // 最后尝试从备用数据源
    fetch_from_backup(id).await
        .map_err(|e| {
            log::error!("所有数据源都失败");
            apperror::dataunavailable(format!("无法获取id为{}的数据", id))
        })
}

4.3 并发错误处理

在异步环境中处理多个并发操作的错误:

use futures::future::join_all;

async fn fetch_multiple_users(
    ids: vec<u32>
) -> result<vec<user>, apperror> {
    let futures: vec<_> = ids
        .into_iter()
        .map(|id| async move {
            fetch_user(id).await
        })
        .collect();
    
    let results = join_all(futures).await;
    
    // 收集所有成功的结果和错误
    let mut users = vec::new();
    let mut errors = vec::new();
    
    for (idx, result) in results.into_iter().enumerate() {
        match result {
            ok(user) => users.push(user),
            err(e) => errors.push((idx, e)),
        }
    }
    
    if !errors.is_empty() {
        log::warn!("部分用户获取失败: {:?}", errors);
        // 根据业务需求决定是返回部分结果还是完全失败
        if users.is_empty() {
            return err(apperror::batchoperationfailed(
                format!("所有用户获取都失败了")
            ));
        }
    }
    
    ok(users)
}

4.4 重试机制

实现智能重试逻辑:

use std::time::duration;
use tokio::time::sleep;

async fn retry_with_backoff<f, t, e>(
    mut operation: f,
    max_retries: u32,
    initial_delay: duration,
) -> result<t, e>
where
    f: fnmut() -> futures::future::boxfuture<'static, result<t, e>>,
    e: std::fmt::display,
{
    let mut delay = initial_delay;
    
    for attempt in 0..max_retries {
        match operation().await {
            ok(result) => return ok(result),
            err(e) => {
                if attempt == max_retries - 1 {
                    log::error!("操作失败,已达最大重试次数: {}", e);
                    return err(e);
                }
                
                log::warn!(
                    "操作失败 (尝试 {}/{}): {}. {}秒后重试...",
                    attempt + 1,
                    max_retries,
                    e,
                    delay.as_secs()
                );
                
                sleep(delay).await;
                delay *= 2; // 指数退避
            }
        }
    }
    
    unreachable!()
}

// 使用示例
async fn fetch_with_retry(url: &str) -> result<response, reqwest::error> {
    retry_with_backoff(
        || box::pin(reqwest::get(url)),
        3,
        duration::from_secs(1),
    ).await
}

第五部分:错误日志与监控

5.1 结构化日志记录

使用tracing库实现结构化日志:

use tracing::{error, warn, info, debug, instrument};

#[instrument(skip(db))]
async fn process_order(
    order_id: u32,
    db: &database,
) -> result<order, apperror> {
    info!(order_id, "开始处理订单");
    
    let order = db.get_order(order_id).await
        .map_err(|e| {
            error!(
                error = %e,
                order_id,
                "获取订单失败"
            );
            apperror::database(e)
        })?;
    
    debug!(order_id, status = ?order.status, "订单状态检查");
    
    if !order.is_valid() {
        warn!(order_id, "订单验证失败");
        return err(apperror::validation {
            field: "order".to_string(),
            message: "订单数据无效".to_string(),
        });
    }
    
    let processed = order.process().await
        .map_err(|e| {
            error!(
                error = %e,
                order_id,
                "订单处理失败"
            );
            apperror::processingfailed(e.to_string())
        })?;
    
    info!(order_id, "订单处理完成");
    ok(processed)
}

5.2 错误度量与监控

集成prometheus进行错误监控:

use prometheus::{intcountervec, histogramvec, register_int_counter_vec, register_histogram_vec};
use lazy_static::lazy_static;

lazy_static! {
    static ref error_counter: intcountervec = register_int_counter_vec!(
        "app_errors_total",
        "应用错误总数",
        &["error_type", "severity"]
    ).unwrap();
    
    static ref request_duration: histogramvec = register_histogram_vec!(
        "request_duration_seconds",
        "请求处理时间",
        &["endpoint", "status"]
    ).unwrap();
}

fn record_error(error: &apperror) {
    let (error_type, severity) = match error {
        apperror::database(_) => ("database", "high"),
        apperror::validation { .. } => ("validation", "low"),
        apperror::unauthorized => ("auth", "medium"),
        apperror::notfound(_) => ("not_found", "low"),
        _ => ("unknown", "medium"),
    };
    
    error_counter
        .with_label_values(&[error_type, severity])
        .inc();
}

async fn handle_request<f, t>(
    endpoint: &str,
    handler: f,
) -> result<t, apperror>
where
    f: future<output = result<t, apperror>>,
{
    let timer = request_duration
        .with_label_values(&[endpoint, "processing"])
        .start_timer();
    
    let result = handler.await;
    
    let status = if result.is_ok() { "success" } else { "error" };
    timer.observe_duration();
    
    request_duration
        .with_label_values(&[endpoint, status])
        .observe(timer.stop_and_record());
    
    if let err(ref e) = result {
        record_error(e);
    }
    
    result
}

5.3 分布式追踪

实现opentelemetry追踪:

use opentelemetry::{global, trace::{tracer, span, status}};
use tracing_opentelemetry::opentelemetryspanext;

async fn traced_operation(
    trace_id: string,
) -> result<(), apperror> {
    let tracer = global::tracer("app");
    let mut span = tracer.start("process_operation");
    
    span.set_attribute(
        opentelemetry::keyvalue::new("trace_id", trace_id.clone())
    );
    
    let result = perform_operation().await;
    
    match &result {
        ok(_) => {
            span.set_status(status::ok);
        }
        err(e) => {
            span.set_status(status::error(e.to_string()));
            span.set_attribute(
                opentelemetry::keyvalue::new("error.type", format!("{:?}", e))
            );
        }
    }
    
    span.end();
    result
}

第六部分:测试错误处理

6.1 单元测试

编写全面的错误处理测试:

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_validation_error() {
        let result = validate_email("");
        assert!(result.is_err());
        
        match result {
            err(apperror::validation { field, message }) => {
                assert_eq!(field, "email");
                assert!(message.contains("不能为空"));
            }
            _ => panic!("期望validationerror"),
        }
    }
    
    #[tokio::test]
    async fn test_database_error_handling() {
        let mock_db = mockdatabase::new();
        mock_db.expect_query()
            .returning(|_| err(databaseerror::connectionfailed("连接超时".into())));
        
        let result = fetch_user_from_db(1, &mock_db).await;
        
        assert!(result.is_err());
        assert!(matches!(result, err(apperror::database(_))));
    }
    
    #[tokio::test]
    async fn test_retry_mechanism() {
        let mut attempt = 0;
        let operation = || {
            attempt += 1;
            async move {
                if attempt < 3 {
                    err(apperror::temporaryerror)
                } else {
                    ok(())
                }
            }
        };
        
        let result = retry_with_backoff(
            operation,
            5,
            duration::from_millis(10),
        ).await;
        
        assert!(result.is_ok());
        assert_eq!(attempt, 3);
    }
}

6.2 集成测试

测试完整的错误处理流程:

#[actix_web::test]
async fn test_api_error_response() {
    let app = test::init_service(
        app::new()
            .service(web::resource("/users/{id}").to(get_user))
    ).await;
    
    // 测试404错误
    let req = test::testrequest::get()
        .uri("/users/99999")
        .to_request();
    let resp = test::call_service(&app, req).await;
    
    assert_eq!(resp.status(), statuscode::not_found);
    
    let body: apiresponse<()> = test::read_body_json(resp).await;
    assert!(!body.success);
    assert!(body.error.is_some());
    assert_eq!(body.error.unwrap().code, "not_found");
}

#[actix_web::test]
async fn test_validation_error_response() {
    let app = test::init_service(
        app::new()
            .service(web::resource("/users").route(web::post().to(create_user)))
    ).await;
    
    let invalid_user = json!({
        "email": "invalid-email",
        "age": -5,
    });
    
    let req = test::testrequest::post()
        .uri("/users")
        .set_json(&invalid_user)
        .to_request();
    
    let resp = test::call_service(&app, req).await;
    assert_eq!(resp.status(), statuscode::bad_request);
}

6.3 错误场景的属性测试

使用proptest进行属性测试:

use proptest::prelude::*;

proptest! {
    #[test]
    fn test_email_validation_properties(
        email in "[a-z]{1,10}@[a-z]{1,10}\\.[a-z]{2,3}"
    ) {
        // 有效的邮箱格式应该通过验证
        let result = validate_email(&email);
        prop_assert!(result.is_ok());
    }
    
    #[test]
    fn test_invalid_email_rejection(
        invalid in "[^@]*"
    ) {
        // 不包含@的字符串应该被拒绝
        if !invalid.contains('@') {
            let result = validate_email(&invalid);
            prop_assert!(result.is_err());
        }
    }
}

第七部分:性能优化

7.1 避免不必要的错误分配

使用引用和借用来减少分配:

// 不好的做法:每次都分配新的错误
fn bad_validation(input: &str) -> result<(), string> {
    if input.is_empty() {
        return err("输入不能为空".to_string());
    }
    ok(())
}

// 好的做法:使用静态字符串或cow
fn good_validation(input: &str) -> result<(), &'static str> {
    if input.is_empty() {
        return err("输入不能为空");
    }
    ok(())
}

// 更好的做法:使用枚举
#[derive(debug)]
enum validationerror {
    empty,
    toolong,
    invalidformat,
}

fn best_validation(input: &str) -> result<(), validationerror> {
    if input.is_empty() {
        return err(validationerror::empty);
    }
    ok(())
}

7.2 错误类型的大小优化

保持错误类型尺寸合理:

// 检查错误类型大小
fn check_error_size() {
    println!("apperror size: {}", std::mem::size_of::<apperror>());
    println!("result<(), apperror> size: {}", 
        std::mem::size_of::<result<(), apperror>>());
}

// 如果错误类型过大,考虑使用box
#[derive(debug)]
enum largeerror {
    bigvariant(box<verylargestruct>),
    smallvariant(u32),
}

7.3 快速路径优化

#[inline]
fn fast_path_check(input: &str) -> result<(), apperror> {
    // 快速路径:常见的成功情况
    if likely(input.len() > 0 && input.len() < 100) {
        return ok(());
    }
    
    // 慢速路径:详细的错误检查
    validate_detailed(input)
}

// 使用likely宏提示编译器优化分支预测
#[inline(always)]
fn likely(b: bool) -> bool {
    if !b {
        core::hint::unreachable_unchecked();
    }
    b
}

第八部分:实战案例

8.1 构建完整的web api错误处理系统

use actix_web::{web, app, httpserver, middleware};
use serde::{deserialize, serialize};

// 应用状态
struct appstate {
    db: database,
    cache: cache,
    config: config,
}

// 请求处理器
#[derive(deserialize)]
struct createuserrequest {
    email: string,
    name: string,
    age: u8,
}

async fn create_user(
    data: web::json<createuserrequest>,
    state: web::data<appstate>,
) -> result<httpresponse, apperror> {
    // 输入验证
    validate_user_input(&data)?;
    
    // 检查用户是否已存在
    if user_exists(&data.email, &state.db).await? {
        return err(apperror::conflict(
            format!("邮箱 {} 已被注册", data.email)
        ));
    }
    
    // 创建用户
    let user = user::new(
        data.email.clone(),
        data.name.clone(),
        data.age,
    );
    
    // 保存到数据库
    let saved_user = state.db
        .insert_user(user)
        .await
        .map_err(|e| {
            log::error!("保存用户失败: {}", e);
            apperror::database(e)
        })?;
    
    // 发送欢迎邮件(失败不影响主流程)
    if let err(e) = send_welcome_email(&saved_user).await {
        log::warn!("发送欢迎邮件失败: {}", e);
    }
    
    // 更新缓存
    state.cache.set_user(&saved_user).await?;
    
    ok(httpresponse::created().json(apiresponse::success(saved_user)))
}

fn validate_user_input(input: &createuserrequest) -> result<(), apperror> {
    if input.email.is_empty() {
        return err(apperror::validation {
            field: "email".to_string(),
            message: "邮箱不能为空".to_string(),
        });
    }
    
    if !is_valid_email(&input.email) {
        return err(apperror::validation {
            field: "email".to_string(),
            message: "邮箱格式无效".to_string(),
        });
    }
    
    if input.name.len() < 2 || input.name.len() > 50 {
        return err(apperror::validation {
            field: "name".to_string(),
            message: "姓名长度必须在2-50个字符之间".to_string(),
        });
    }
    
    if input.age < 18 {
        return err(apperror::validation {
            field: "age".to_string(),
            message: "年龄必须大于18岁".to_string(),
        });
    }
    
    ok(())
}

#[actix_web::main]
async fn main() -> std::io::result<()> {
    // 初始化日志
    tracing_subscriber::fmt::init();
    
    // 初始化应用状态
    let state = web::data::new(appstate {
        db: database::connect().await.unwrap(),
        cache: cache::new(),
        config: config::load().unwrap(),
    });
    
    httpserver::new(move || {
        app::new()
            .app_data(state.clone())
            .wrap(middleware::logger::default())
            .wrap(errorhandlers::new
```        .wrap(middleware::compress::default())
            .service(
                web::scope("/api/v1")
                    .service(
                        web::resource("/users")
                            .route(web::post().to(create_user))
                            .route(web::get().to(list_users))
                    )
                    .service(
                        web::resource("/users/{id}")
                            .route(web::get().to(get_user))
                            .route(web::put().to(update_user))
                            .route(web::delete().to(delete_user))
                    )
            )
            .default_service(web::route().to(not_found))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

async fn not_found() -> result<httpresponse, apperror> {
    err(apperror::notfound("请求的资源不存在".to_string()))
}

8.2 数据库事务中的错误处理

use sqlx::{pgpool, postgres, transaction};

async fn transfer_funds(
    from_account: u32,
    to_account: u32,
    amount: f64,
    pool: &pgpool,
) -> result<transferresult, apperror> {
    // 开始事务
    let mut tx = pool.begin().await
        .map_err(|e| apperror::database(e.into()))?;
    
    // 检查源账户余额
    let from_balance = get_account_balance(&mut tx, from_account).await?;
    
    if from_balance < amount {
        return err(apperror::insufficientfunds {
            account_id: from_account,
            available: from_balance,
            requested: amount,
        });
    }
    
    // 扣款
    deduct_from_account(&mut tx, from_account, amount)
        .await
        .map_err(|e| {
            log::error!("扣款失败: account={}, amount={}, error={}", 
                from_account, amount, e);
            apperror::transactionfailed(format!("扣款操作失败: {}", e))
        })?;
    
    // 入账
    add_to_account(&mut tx, to_account, amount)
        .await
        .map_err(|e| {
            log::error!("入账失败: account={}, amount={}, error={}", 
                to_account, amount, e);
            // 事务会自动回滚
            apperror::transactionfailed(format!("入账操作失败: {}", e))
        })?;
    
    // 记录转账历史
    record_transfer(&mut tx, from_account, to_account, amount)
        .await
        .map_err(|e| {
            log::warn!("记录转账历史失败: {}", e);
            // 即使记录失败,也不影响主要转账操作
            e
        })
        .ok();
    
    // 提交事务
    tx.commit().await
        .map_err(|e| apperror::database(e.into()))?;
    
    log::info!("转账成功: {} -> {}, 金额: {}", 
        from_account, to_account, amount);
    
    ok(transferresult {
        from_account,
        to_account,
        amount,
        timestamp: chrono::utc::now(),
    })
}

async fn get_account_balance(
    tx: &mut transaction<'_, postgres>,
    account_id: u32,
) -> result<f64, apperror> {
    sqlx::query_scalar("select balance from accounts where id = $1")
        .bind(account_id)
        .fetch_optional(tx)
        .await
        .map_err(|e| apperror::database(e.into()))?
        .ok_or_else(|| apperror::notfound(
            format!("账户 {} 不存在", account_id)
        ))
}

8.3 外部api调用的错误处理

use reqwest::{client, statuscode};
use serde_json::value;

async fn call_external_api(
    endpoint: &str,
    payload: value,
) -> result<value, apperror> {
    let client = client::new();
    
    let response = client
        .post(endpoint)
        .json(&payload)
        .timeout(duration::from_secs(30))
        .send()
        .await
        .map_err(|e| {
            if e.is_timeout() {
                apperror::externalservicetimeout {
                    service: endpoint.to_string(),
                    duration: duration::from_secs(30),
                }
            } else if e.is_connect() {
                apperror::externalserviceunavailable {
                    service: endpoint.to_string(),
                    reason: "连接失败".to_string(),
                }
            } else {
                apperror::externalserviceerror {
                    service: endpoint.to_string(),
                    message: e.to_string(),
                }
            }
        })?;
    
    match response.status() {
        statuscode::ok => {
            response.json().await
                .map_err(|e| apperror::serialization(e.into()))
        }
        statuscode::bad_request => {
            let error_body: value = response.json().await
                .unwrap_or(json!({"error": "未知错误"}));
            err(apperror::externalservicebadrequest {
                service: endpoint.to_string(),
                details: error_body,
            })
        }
        statuscode::unauthorized | statuscode::forbidden => {
            err(apperror::externalserviceauth {
                service: endpoint.to_string(),
                status: response.status().as_u16(),
            })
        }
        statuscode::not_found => {
            err(apperror::externalservicenotfound {
                service: endpoint.to_string(),
                resource: payload.to_string(),
            })
        }
        statuscode::too_many_requests => {
            let retry_after = response
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse().ok())
                .unwrap_or(60);
            
            err(apperror::ratelimitexceeded {
                service: endpoint.to_string(),
                retry_after: duration::from_secs(retry_after),
            })
        }
        status if status.is_server_error() => {
            err(apperror::externalserviceerror {
                service: endpoint.to_string(),
                message: format!("服务器错误: {}", status),
            })
        }
        _ => {
            err(apperror::externalserviceerror {
                service: endpoint.to_string(),
                message: format!("未预期的状态码: {}", response.status()),
            })
        }
    }
}

// 带重试的外部api调用
async fn call_external_api_with_retry(
    endpoint: &str,
    payload: value,
) -> result<value, apperror> {
    let max_retries = 3;
    let mut last_error = none;
    
    for attempt in 0..max_retries {
        match call_external_api(endpoint, payload.clone()).await {
            ok(result) => return ok(result),
            err(e) => {
                match &e {
                    apperror::externalservicetimeout { .. }
                    | apperror::externalserviceunavailable { .. } => {
                        // 可重试的错误
                        last_error = some(e);
                        
                        if attempt < max_retries - 1 {
                            let delay = duration::from_secs(2_u64.pow(attempt));
                            log::warn!(
                                "api调用失败,{}秒后重试 (尝试 {}/{})",
                                delay.as_secs(),
                                attempt + 1,
                                max_retries
                            );
                            tokio::time::sleep(delay).await;
                        }
                    }
                    apperror::ratelimitexceeded { retry_after, .. } => {
                        // 速率限制,等待指定时间后重试
                        if attempt < max_retries - 1 {
                            log::warn!(
                                "触发速率限制,等待{}秒后重试",
                                retry_after.as_secs()
                            );
                            tokio::time::sleep(*retry_after).await;
                            last_error = some(e);
                        } else {
                            return err(e);
                        }
                    }
                    _ => {
                        // 不可重试的错误,直接返回
                        return err(e);
                    }
                }
            }
        }
    }
    
    err(last_error.unwrap_or_else(|| apperror::unknown(
        "api调用失败但未记录错误".to_string()
    )))
}

8.4 文件处理的错误处理

use tokio::fs::{file, openoptions};
use tokio::io::{asyncreadext, asyncwriteext};

async fn process_uploaded_file(
    file_path: &str,
    content_type: &str,
) -> result<fileinfo, apperror> {
    // 验证文件类型
    validate_file_type(content_type)?;
    
    // 读取文件
    let mut file = file::open(file_path)
        .await
        .map_err(|e| apperror::fileoperation {
            operation: "open".to_string(),
            path: file_path.to_string(),
            source: e,
        })?;
    
    let mut buffer = vec::new();
    file.read_to_end(&mut buffer)
        .await
        .map_err(|e| apperror::fileoperation {
            operation: "read".to_string(),
            path: file_path.to_string(),
            source: e,
        })?;
    
    // 验证文件大小
    const max_size: usize = 10 * 1024 * 1024; // 10mb
    if buffer.len() > max_size {
        return err(apperror::filetoolarge {
            size: buffer.len(),
            max_size: max_size,
        });
    }
    
    // 验证文件内容
    validate_file_content(&buffer, content_type)?;
    
    // 生成安全的文件名
    let safe_filename = generate_safe_filename(file_path)?;
    let storage_path = format!("uploads/{}", safe_filename);
    
    // 保存文件
    let mut output_file = openoptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(&storage_path)
        .await
        .map_err(|e| apperror::fileoperation {
            operation: "create".to_string(),
            path: storage_path.clone(),
            source: e,
        })?;
    
    output_file.write_all(&buffer)
        .await
        .map_err(|e| apperror::fileoperation {
            operation: "write".to_string(),
            path: storage_path.clone(),
            source: e,
        })?;
    
    output_file.sync_all()
        .await
        .map_err(|e| apperror::fileoperation {
            operation: "sync".to_string(),
            path: storage_path.clone(),
            source: e,
        })?;
    
    ok(fileinfo {
        original_name: file_path.to_string(),
        storage_path,
        size: buffer.len(),
        content_type: content_type.to_string(),
        uploaded_at: chrono::utc::now(),
    })
}

fn validate_file_type(content_type: &str) -> result<(), apperror> {
    const allowed_types: &[&str] = &[
        "image/jpeg",
        "image/png",
        "image/gif",
        "application/pdf",
    ];
    
    if !allowed_types.contains(&content_type) {
        return err(apperror::invalidfiletype {
            provided: content_type.to_string(),
            allowed: allowed_types.iter().map(|s| s.to_string()).collect(),
        });
    }
    
    ok(())
}

fn validate_file_content(
    buffer: &[u8],
    expected_type: &str,
) -> result<(), apperror> {
    // 验证文件魔数(文件头)
    let magic_bytes = &buffer[..std::cmp::min(16, buffer.len())];
    
    let is_valid = match expected_type {
        "image/jpeg" => magic_bytes.starts_with(&[0xff, 0xd8, 0xff]),
        "image/png" => magic_bytes.starts_with(&[0x89, 0x50, 0x4e, 0x47]),
        "image/gif" => magic_bytes.starts_with(b"gif87a") 
            || magic_bytes.starts_with(b"gif89a"),
        "application/pdf" => magic_bytes.starts_with(b"%pdf"),
        _ => true, // 其他类型跳过验证
    };
    
    if !is_valid {
        return err(apperror::filecontentmismatch {
            declared_type: expected_type.to_string(),
            message: "文件内容与声明类型不匹配".to_string(),
        });
    }
    
    ok(())
}

第九部分:领域特定错误处理

9.1 认证与授权错误

#[derive(error, debug)]
pub enum autherror {
    #[error("无效的凭证")]
    invalidcredentials,
    
    #[error("令牌已过期")]
    tokenexpired,
    
    #[error("令牌无效: {0}")]
    invalidtoken(string),
    
    #[error("缺少认证信息")]
    missingauth,
    
    #[error("权限不足: 需要 {required}, 当前 {current}")]
    insufficientpermissions {
        required: string,
        current: string,
    },
    
    #[error("账户已锁定: {reason}")]
    accountlocked {
        reason: string,
        locked_until: option<chrono::datetime<chrono::utc>>,
    },
}

async fn authenticate_user(
    email: &str,
    password: &str,
    db: &database,
) -> result<user, autherror> {
    // 查找用户
    let user = db.find_user_by_email(email)
        .await
        .map_err(|_| autherror::invalidcredentials)?;
    
    // 检查账户状态
    if user.is_locked() {
        return err(autherror::accountlocked {
            reason: "多次登录失败".to_string(),
            locked_until: user.locked_until,
        });
    }
    
    // 验证密码
    if !verify_password(password, &user.password_hash)? {
        // 记录失败尝试
        db.record_failed_login(&user.id).await.ok();
        
        // 检查是否需要锁定账户
        let failed_attempts = db.get_failed_login_count(&user.id).await?;
        if failed_attempts >= 5 {
            db.lock_account(&user.id, duration::from_secs(1800)).await?;
            return err(autherror::accountlocked {
                reason: "连续登录失败超过5次".to_string(),
                locked_until: some(chrono::utc::now() + chrono::duration::minutes(30)),
            });
        }
        
        return err(autherror::invalidcredentials);
    }
    
    // 重置失败计数
    db.reset_failed_login_count(&user.id).await.ok();
    
    ok(user)
}

// 权限检查中间件
async fn check_permissions(
    req: servicerequest,
    required_permission: &str,
) -> result<servicerequest, actix_web::error> {
    let token = extract_token(&req)
        .ok_or(autherror::missingauth)?;
    
    let claims = validate_token(&token)
        .map_err(|e| autherror::invalidtoken(e.to_string()))?;
    
    if !claims.permissions.contains(&required_permission.to_string()) {
        return err(autherror::insufficientpermissions {
            required: required_permission.to_string(),
            current: claims.permissions.join(", "),
        }.into());
    }
    
    ok(req)
}

9.2 支付处理错误

#[derive(error, debug)]
pub enum paymenterror {
    #[error("支付金额无效: {0}")]
    invalidamount(f64),
    
    #[error("余额不足: 可用 {available}, 需要 {required}")]
    insufficientfunds {
        available: f64,
        required: f64,
    },
    
    #[error("支付方式不支持: {0}")]
    unsupportedpaymentmethod(string),
    
    #[error("支付处理失败: {reason}")]
    processingfailed {
        reason: string,
        transaction_id: option<string>,
    },
    
    #[error("支付网关错误: {gateway} - {message}")]
    gatewayerror {
        gateway: string,
        message: string,
        error_code: option<string>,
    },
    
    #[error("重复支付: 订单 {order_id} 已支付")]
    duplicatepayment {
        order_id: string,
        existing_transaction: string,
    },
}

async fn process_payment(
    order: &order,
    payment_method: paymentmethod,
    gateway: &paymentgateway,
) -> result<paymentresult, paymenterror> {
    // 验证支付金额
    if order.total <= 0.0 {
        return err(paymenterror::invalidamount(order.total));
    }
    
    // 检查订单状态
    if order.is_paid() {
        return err(paymenterror::duplicatepayment {
            order_id: order.id.to_string(),
            existing_transaction: order.payment_transaction.clone()
                .unwrap_or_default(),
        });
    }
    
    // 验证支付方式
    if !is_payment_method_supported(&payment_method) {
        return err(paymenterror::unsupportedpaymentmethod(
            format!("{:?}", payment_method)
        ));
    }
    
    // 调用支付网关
    let payment_request = paymentrequest {
        amount: order.total,
        currency: order.currency.clone(),
        order_id: order.id.to_string(),
        payment_method,
        customer: order.customer.clone(),
    };
    
    let result = gateway
        .process_payment(payment_request)
        .await
        .map_err(|e| match e {
            gatewayerror::insufficientfunds { available, required } => {
                paymenterror::insufficientfunds { available, required }
            }
            gatewayerror::networkerror(msg) => {
                paymenterror::gatewayerror {
                    gateway: gateway.name().to_string(),
                    message: format!("网络错误: {}", msg),
                    error_code: none,
                }
            }
            gatewayerror::apierror { code, message } => {
                paymenterror::gatewayerror {
                    gateway: gateway.name().to_string(),
                    message,
                    error_code: some(code),
                }
            }
            _ => paymenterror::processingfailed {
                reason: e.to_string(),
                transaction_id: none,
            },
        })?;
    
    // 记录支付结果
    log::info!(
        "支付成功: order={}, transaction={}, amount={}",
        order.id,
        result.transaction_id,
        order.total
    );
    
    ok(result)
}

// 支付失败后的补偿处理
async fn handle_payment_failure(
    order: &order,
    error: &paymenterror,
    db: &database,
) -> result<(), apperror> {
    // 记录失败原因
    db.record_payment_failure(order.id, error).await?;
    
    // 发送通知
    match error {
        paymenterror::insufficientfunds { .. } => {
            notify_insufficient_funds(&order.customer).await?;
        }
        paymenterror::gatewayerror { .. } => {
            notify_technical_issue(&order.customer).await?;
            // 通知技术团队
            alert_ops_team(format!("支付网关错误: {:?}", error)).await?;
        }
        _ => {
            notify_payment_failed(&order.customer, error).await?;
        }
    }
    
    // 更新订单状态
    db.update_order_status(order.id, orderstatus::paymentfailed).await?;
    
    ok(())
}

9.3 数据验证错误

use validator::{validate, validationerror};

#[derive(debug, validate, deserialize)]
struct userregistration {
    #[validate(email(message = "邮箱格式无效"))]
    email: string,
    
    #[validate(length(min = 8, message = "密码长度至少8位"))]
    #[validate(custom = "validate_password_strength")]
    password: string,
    
    #[validate(length(min = 2, max = 50, message = "用户名长度必须在2-50之间"))]
    #[validate(regex(path = "username_regex", message = "用户名只能包含字母、数字和下划线"))]
    username: string,
    
    #[validate(range(min = 18, max = 120, message = "年龄必须在18-120之间"))]
    age: u8,
    
    #[validate(phone(message = "手机号格式无效"))]
    phone: option<string>,
}

lazy_static! {
    static ref username_regex: regex::regex = 
        regex::regex::new(r"^[a-za-z0-9_]+$").unwrap();
}

fn validate_password_strength(password: &str) -> result<(), validationerror> {
    let has_uppercase = password.chars().any(|c| c.is_uppercase());
    let has_lowercase = password.chars().any(|c| c.is_lowercase());
    let has_digit = password.chars().any(|c| c.is_numeric());
    let has_special = password.chars().any(|c| "!@#$%^&*()".contains(c));
    
    if !(has_uppercase && has_lowercase && has_digit && has_special) {
        return err(validationerror::new("weak_password")
            .with_message(std::borrow::cow::borrowed(
                "密码必须包含大小写字母、数字和特殊字符"
            )));
    }
    
    ok(())
}

async fn register_user(
    data: web::json<userregistration>,
    db: web::data<database>,
) -> result<httpresponse, apperror> {
    // 使用validator进行验证
    data.validate()
        .map_err(|e| apperror::validationerrors(e))?;
    
    // 额外的业务逻辑验证
    validate_business_rules(&data, &db).await?;
    
    // 创建用户
    let user = create_user_from_registration(&data).await?;
    
    ok(httpresponse::created().json(apiresponse::success(user)))
}

async fn validate_business_rules(
    data: &userregistration,
    db: &database,
) -> result<(), apperror> {
    // 检查邮箱是否已被使用
    if db.email_exists(&data.email).await? {
        return err(apperror::validation {
            field: "email".to_string(),
            message: "该邮箱已被注册".to_string(),
        });
    }
    
    // 检查用户名是否已被使用
    if db.username_exists(&data.username).await? {
        return err(apperror::validation {
            field: "username".to_string(),
            message: "该用户名已被占用".to_string(),
        });
    }
    
    // 检查是否在黑名单中
    if is_email_blacklisted(&data.email) {
        return err(apperror::validation {
            field: "email".to_string(),
            message: "该邮箱域名不被支持".to_string(),
        });
    }
    
    ok(())
}

// 将validator的错误转换为应用错误
impl from<validator::validationerrors> for apperror {
    fn from(errors: validator::validationerrors) -> self {
        let mut messages = vec::new();
        
        for (field, errors) in errors.field_errors() {
            for error in errors {
                let message = error
                    .message
                    .clone()
                    .unwrap_or_else(|| std::borrow::cow::borrowed("验证失败"));
                
                messages.push(format!("{}: {}", field, message));
            }
        }
        
        apperror::validationerrors {
            fields: messages,
        }
    }
}

第十部分:错误恢复策略

10.1 断路器模式

use std::sync::arc;
use tokio::sync::rwlock;

#[derive(clone)]
pub struct circuitbreaker {
    state: arc<rwlock<circuitstate>>,
    config: circuitconfig,
}

#[derive(debug)]
enum circuitstate {
    closed {
        failure_count: u32,
    },
    open {
        opened_at: instant,
    },
    halfopen {
        success_count: u32,
        failure_count: u32,
    },
}

struct circuitconfig {
    failure_threshold: u32,
    timeout: duration,
    half_open_max_calls: u32,
}

impl circuitbreaker {
    pub fn new(config: circuitconfig) -> self {
        self {
            state: arc::new(rwlock::new(circuitstate::closed {
                failure_count: 0,
            })),
            config,
        }
    }
    
    pub async fn call<f, t, e>(&self, operation: f) -> result<t, circuitbreakererror<e>>
    where
        f: future<output = result<t, e>>,
        e: std::fmt::display,
    {
        // 检查断路器状态
        {
            let state = self.state.read().await;
            match *state {
                circuitstate::open { opened_at } => {
                    if opened_at.elapsed() < self.config.timeout {
                        return err(circuitbreakererror::open);
                    }
                    // 超时后进入半开状态
                }
                _ => {}
            }
        }
        
        // 执行操作
        let result = operation.await;
        
        // 更新状态
        self.handle_result(&result).await;
        
        result.map_err(circuitbreakererror::inner)
    }
    
    async fn handle_result<t, e>(&self, result: &result<t, e>) {
        let mut state = self.state.write().await;
        
        match &mut *state {
            circuitstate::closed { failure_count } => {
                if result.is_err() {
                    *failure_count += 1;
                    
                    if *failure_count >= self.config.failure_threshold {
                        log::warn!("断路器打开: 失败次数达到阈值");
                        *state = circuitstate::open {
                            opened_at: instant::now(),
                        };
                    }
                } else {
                    *failure_count = 0;
                }
            }
            circuitstate::open { opened_at } => {
                if opened_at.elapsed() >= self.config.timeout {
                    log::info!("断路器进入半开状态");
                    *state = circuitstate::halfopen {
                        success_count: 0,
                        failure_count: 0,
                    };
                }
            }
            circuitstate::halfopen {
                success_count,
                failure_count,
            } => {
                if result.is_ok() {
                    *success_count += 1;
                    
                    if *success_count >= self.config.half_open_max_calls {
                        log::info!("断路器关闭: 测试调用成功");
                        *state = circuitstate::closed { failure_count: 0 };
                    }
                } else {
                    *failure_count += 1;
                    log::warn!("断路器重新打开: 测试调用失败");
                    *state = circuitstate::open {
                        opened_at: instant::now(),
                    };
                }
            }
        }
    }
}

#[derive(error, debug)]
pub enum circuitbreakererror<e> {
    #[error("断路器打开")]
    open,
    
    #[error("操作失败: {0}")]
    inner(e),
}

// 使用示例
async fn call_external_service_with_circuit_breaker(
    circuit_breaker: &circuitbreaker,
    request: request,
) -> result<response, apperror> {
    circuit_breaker
        .call(async {
            call_external_service(request).await
        })
        .await
        .map_err(|e| match e {
            circuitbreakererror::open => {
                apperror::serviceunavailable {
                    service: "external_api".to_string(),
                    reason: "断路器打开".to_string(),
                }
            }
            circuitbreakererror::inner(e) => e,
        })
}

10.2 降级策略

async fn get_user_with_fallback(
    user_id: u32,
    services: &services,
) -> result<user, apperror> {
    // 第一级:尝试从主数据库获取
    match services.primary_db.get_user(user_id).await {
        ok(user) => {
            log::debug!("从主数据库获取用户成功: {}", user_id);
            return ok(user);
        }
        err(e) => {
            log::warn!("主数据库失败: {}, 尝试缓存", e);
        }
    }
    
    // 第二级:尝试从缓存获取
    match services.cache.get_user(user_id).await {
        ok(some(user)) => {
            log::info!("从缓存获取用户成功: {}", user_id);
            return ok(user);
        }
        ok(none) => {
            log::debug!("缓存中不存在用户: {}", user_id);
        }
        err(e) => {
            log::warn!("缓存获取失败: {}", e);
        }
    }
    
    // 第三级:尝试从只读副本获取
    match services.read_replica.get_user(user_id).await {
        ok(user) => {
            log::info!("从只读副本获取用户成功: {}", user_id);
            // 异步更新缓存
            let cache = services.cache.clone();
            let user_clone = user.clone();
            tokio::spawn(async move {
                if let err(e) = cache.set_user(&user_clone).await {
                    log::error!("更新缓存失败: {}", e);
                }
            });
            return ok(user);
        }
        err(e) => {
            log::error!("所有数据源都失败: {}", e);
        }
    }
    
    // 第四级:返回默认用户(最后的降级)
    log::error!("无法获取用户 {}, 返回默认用户", user_id);
    ok(user::guest_user())
}

// 功能降级装饰器
async fn with_graceful_degradation<f, t>(
    operation: f,
    fallback: t,
    operation_name: &str,
) -> t
where
    f: future<output = result<t, apperror>>,
{
    match operation.await {
        ok(result) => result,
        err(e) => {
            log::warn!(
                "操作 {} 失败: {}, 使用降级方案",
                operation_name,
                e
            );
            
            // 记录降级事件
            metrics::counter!("degradation_events", 1, "operation" => operation_name);
            
            fallback
        }
    }
}

// 使用示例
async fn get_user_recommendations(
    user_id: u32,
    services: &services,
) -> vec<recommendation> {
    with_graceful_degradation(
        services.recommendation_engine.get_recommendations(user_id),
        vec![], // 降级:返回空列表
        "user_recommendations",
    ).await
}

async fn get_user_profile_with_degradation(
    user_id: u32,
    services: &services,
) -> userprofile {
    let user = with_graceful_degradation(
        services.db.get_user(user_id),
        user::guest_user(),
        "get_user",
    ).await;
    
    let preferences = with_graceful_degradation(
        services.db.get_preferences(user_id),
        preferences::default(),
        "get_preferences",
    ).await;
    
    let stats = with_graceful_degradation(
        services.analytics.get_user_stats(user_id),
        userstats::default(),
        "get_user_stats",
    ).await;
    
    userprofile {
        user,
        preferences,
        stats,
    }
}

10.3 补偿事务(saga模式)

use async_trait::async_trait;

#[async_trait]
trait sagastep: send + sync {
    async fn execute(&self) -> result<(), apperror>;
    async fn compensate(&self) -> result<(), apperror>;
}

struct createorderstep {
    order_data: orderdata,
    db: arc<database>,
}

#[async_trait]
impl sagastep for createorderstep {
    async fn execute(&self) -> result<(), apperror> {
        self.db.create_order(&self.order_data).await?;
        log::info!("订单创建成功: {}", self.order_data.id);
        ok(())
    }
    
    async fn compensate(&self) -> result<(), apperror> {
        self.db.delete_order(self.order_data.id).await?;
        log::info!("订单回滚: {}", self.order_data.id);
        ok(())
    }
}

struct reserveinventorystep {
    order_id: u32,
    items: vec<orderitem>,
    inventory_service: arc<inventoryservice>,
}

#[async_trait]
impl sagastep for reserveinventorystep {
    async fn execute(&self) -> result<(), apperror> {
        for item in &self.items {
            self.inventory_service
                .reserve(item.product_id, item.quantity)
                .await?;
        }
        log::info!("库存预留成功: order={}", self.order_id);
        ok(())
    }
    
    async fn compensate(&self) -> result<(), apperror> {
        for item in &self.items {
            self.inventory_service
                .release_reservation(item.product_id, item.quantity)
                .await?;
        }
        log::info!("库存预留回滚: order={}", self.order_id);
        ok(())
    }
}

struct processpaymentstep {
    order_id: u32,
    amount: f64,
    payment_service: arc<paymentservice>,
}

#[async_trait]
impl sagastep for processpaymentstep {
    async fn execute(&self) -> result<(), apperror> {
        self.payment_service
            .charge(self.order_id, self.amount)
            .await?;
        log::info!("支付处理成功: order={}, amount={}", self.order_id, self.amount);
        ok(())
    }
    
    async fn compensate(&self) -> result<(), apperror> {
        self.payment_service
            .refund(self.order_id, self.amount)
            .await?;
        log::info!("支付退款: order={}, amount={}", self.order_id, self.amount);
        ok(())
    }
}

struct saga {
    steps: vec<box<dyn sagastep>>,
    executed_steps: vec<usize>,
}

impl saga {
    fn new() -> self {
        self {
            steps: vec::new(),
            executed_steps: vec::new(),
        }
    }
    
    fn add_step(&mut self, step: box<dyn sagastep>) {
        self.steps.push(step);
    }
    
    async fn execute(&mut self) -> result<(), apperror> {
        for (index, step) in self.steps.iter().enumerate() {
            match step.execute().await {
                ok(_) => {
                    self.executed_steps.push(index);
                }
                err(e) => {
                    log::error!("saga步骤失败: step={}, error={}", index, e);
                    // 执行补偿
                    self.compensate().await?;
                    return err(e);
                }
            }
        }
        
        ok(())
    }
    
    async fn compensate(&self) -> result<(), apperror> {
        log::warn!("开始saga补偿事务");
        
        // 按相反顺序执行补偿
        for &index in self.executed_steps.iter().rev() {
            if let some(step) = self.steps.get(index) {
                if let err(e) = step.compensate().await {
                    log::error!("补偿步骤失败: step={}, error={}", index, e);
                    // 继续执行其他补偿,不要中断
                }
            }
        }
        
        log::info!("saga补偿事务完成");
        ok(())
    }
}

// 使用示例
async fn process_order_with_saga(
    order_data: orderdata,
    services: &services,
) -> result<order, apperror> {
    let mut saga = saga::new();
    
    // 添加创建订单步骤
    saga.add_step(box::new(createorderstep {
        order_data: order_data.clone(),
        db: services.db.clone(),
    }));
    
    // 添加预留库存步骤
    saga.add_step(box::new(reserveinventorystep {
        order_id: order_data.id,
        items: order_data.items.clone(),
        inventory_service: services.inventory.clone(),
    }));
    
    // 添加支付处理步骤
    saga.add_step(box::new(processpaymentstep {
        order_id: order_data.id,
        amount: order_data.total,
        payment_service: services.payment.clone(),
    }));
    
    // 执行saga
    saga.execute().await?;
    
    // 获取完整的订单信息
    let order = services.db.get_order(order_data.id).await?;
    
    log::info!("订单处理完成: {}", order_data.id);
    ok(order)
}

10.4 幂等性处理

use uuid::uuid;

struct idempotencykey(string);

impl idempotencykey {
    fn new() -> self {
        self(uuid::new_v4().to_string())
    }
    
    fn from_request(req: &httprequest) -> option<self> {
        req.headers()
            .get("idempotency-key")
            .and_then(|v| v.to_str().ok())
            .map(|s| self(s.to_string()))
    }
}

struct idempotencystore {
    redis: redis::client,
}

impl idempotencystore {
    async fn check_and_store(
        &self,
        key: &idempotencykey,
        ttl: duration,
    ) -> result<idempotencystatus, apperror> {
        let mut conn = self.redis.get_async_connection().await
            .map_err(|e| apperror::cache(e.into()))?;
        
        let exists: bool = redis::cmd("exists")
            .arg(&key.0)
            .query_async(&mut conn)
            .await
            .map_err(|e| apperror::cache(e.into()))?;
        
        if exists {
            // 获取之前的结果
            let result: option<string> = redis::cmd("get")
                .arg(&key.0)
                .query_async(&mut conn)
                .await
                .map_err(|e| apperror::cache(e.into()))?;
            
            return ok(idempotencystatus::duplicate(result));
        }
        
        // 设置处理中状态
        redis::cmd("setex")
            .arg(&key.0)
            .arg(ttl.as_secs())
            .arg("processing")
            .query_async(&mut conn)
            .await
            .map_err(|e| apperror::cache(e.into()))?;
        
        ok(idempotencystatus::new)
    }
    
    async fn store_result(
        &self,
        key: &idempotencykey,
        result: &str,
        ttl: duration,
    ) -> result<(), apperror> {
        let mut conn = self.redis.get_async_connection().await
            .map_err(|e| apperror::cache(e.into()))?;
        
        redis::cmd("setex")
            .arg(&key.0)
            .arg(ttl.as_secs())
            .arg(result)
            .query_async(&mut conn)
            .await
            .map_err(|e| apperror::cache(e.into()))?;
        
        ok(())
    }
}

enum idempotencystatus {
    new,
    duplicate(option<string>),
}

// 幂等性中间件
async fn idempotent_handler<f, t>(
    req: httprequest,
    handler: f,
    store: &idempotencystore,
) -> result<httpresponse, apperror>
where
    f: future<output = result<t, apperror>>,
    t: serialize,
{
    let idempotency_key = idempotencykey::from_request(&req)
        .ok_or_else(|| apperror::missingidempotencykey)?;
    
    match store.check_and_store(&idempotency_key, duration::from_secs(86400)).await? {
        idempotencystatus::new => {
            // 执行操作
            let result = handler.await?;
            
            // 存储结果
            let result_json = serde_json::to_string(&result)
                .map_err(|e| apperror::serialization(e.into()))?;
            
            store.store_result(
                &idempotency_key,
                &result_json,
                duration::from_secs(86400),
            ).await?;
            
            ok(httpresponse::ok().json(result))
        }
        idempotencystatus::duplicate(some(cached_result)) => {
            // 返回缓存的结果
            log::info!("幂等请求,返回缓存结果");
            ok(httpresponse::ok()
                .content_type("application/json")
                .body(cached_result))
        }
        idempotencystatus::duplicate(none) => {
            // 正在处理中
            err(apperror::requestinprogress)
        }
    }
}

// 使用示例
async fn create_payment_idempotent(
    req: httprequest,
    data: web::json<paymentrequest>,
    state: web::data<appstate>,
) -> result<httpresponse, apperror> {
    idempotent_handler(
        req,
        async {
            process_payment(&data, &state.payment_service).await
        },
        &state.idempotency_store,
    ).await
}

第十一部分:错误文档化与沟通

11.1 错误代码体系

// 定义标准化的错误代码
pub mod error_codes {
    pub const validation_error: &str = "e1000";
    pub const missing_field: &str = "e1001";
    pub const invalid_format: &str = "e1002";
    pub const out_of_range: &str = "e1003";
    
    pub const auth_error: &str = "e2000";
    pub const invalid_credentials: &str = "e2001";
    pub const token_expired: &str = "e2002";
    pub const insufficient_permissions: &str = "e2003";
    
    pub const database_error: &str = "e3000";
    pub const connection_failed: &str = "e3001";
    pub const query_failed: &str = "e3002";
    pub const constraint_violation: &str = "e3003";
    
    pub const business_error: &str = "e4000";
    pub const insufficient_funds: &str = "e4001";
    pub const duplicate_operation: &str = "e4002";
    pub const resource_locked: &str = "e4003";
}

#[derive(debug, serialize)]
struct detailederrorresponse {
    // 错误代码
    code: string,
    
    // 面向用户的错误消息
    message: string,
    
    // 面向开发者的详细信息
    details: option<string>,
    
    // 错误发生的时间
    timestamp: chrono::datetime<chrono::utc>,
    
    // 请求追踪id
    trace_id: string,
    
    // 相关文档链接
    documentation_url: option<string>,
    
    // 建议的解决方案
    suggestions: vec<string>,
}

impl apperror {
    fn to_detailed_response(&self, trace_id: string) -> detailederrorresponse {
        let (code, message, details, doc_url, suggestions) = match self {
            apperror::validation { field, message } => (
                error_codes::validation_error,
                format!("验证失败: {}", message),
                some(format!("字段 '{}' 的值不符合要求", field)),
                some("https://docs.example.com/errors/validation".to_string()),
                vec![
                    "检查输入格式是否正确".to_string(),
                    "参考api文档了解字段要求".to_string(),
                ],
            ),
            
            apperror::unauthorized => (
                error_codes::auth_error,
                "未授权访问".to_string(),
                some("需要有效的认证凭证".to_string()),
                some("https://docs.example.com/errors/auth".to_string()),
                vec![
                    "确保请求包含有效的认证令牌".to_string(),
                    "检查令牌是否已过期".to_string(),
                    "联系管理员获取访问权限".to_string(),
                ],
            ),
            
            apperror::insufficientfunds { available, required, .. } => (
                error_codes::insufficient_funds,
                "余额不足".to_string(),
                some(format!("可用余额: {}, 需要: {}", available, required)),
                some("https://docs.example.com/errors/payment".to_string()),
                vec![
                    "充值账户".to_string(),
                    "选择其他支付方式".to_string(),
                    "减少交易金额".to_string(),
                ],
            ),
            
            _ => (
                "e9999",
                "内部服务器错误".to_string(),
                none,
                some("https://docs.example.com/errors/general".to_string()),
                vec![
                    "稍后重试".to_string(),
                    "如果问题持续,请联系技术支持".to_string(),
                ],
            ),
        };
        
        detailederrorresponse {
            code: code.to_string(),
            message,
            details,
            timestamp: chrono::utc::now(),
            trace_id,
            documentation_url: doc_url,
            suggestions,
        }
    }
}

11.2 多语言错误消息

use std::collections::hashmap;

struct errormessagecatalog {
    messages: hashmap<string, hashmap<string, string>>,
}

impl errormessagecatalog {
    fn new() -> self {
        let mut messages = hashmap::new();
        
        // 英文消息
        let mut en = hashmap::new();
        en.insert("validation.required".to_string(), "this field is required".to_string());
        en.insert("validation.email".to_string(), "invalid email format".to_string());
        en.insert("auth.invalid_credentials".to_string(), "invalid username or password".to_string());
        messages.insert("en".to_string(), en);
        
        // 中文消息
        let mut zh = hashmap::new();
        zh.insert("validation.required".to_string(), "此字段为必填项".to_string());
        zh.insert("validation.email".to_string(), "邮箱格式无效".to_string());
        zh.insert("auth.invalid_credentials".to_string(), "用户名或密码错误".to_string());
        messages.insert("zh".to_string(), zh);
        
        self { messages }
    }
    
    fn get_message(&self, key: &str, locale: &str) -> string {
        self.messages
            .get(locale)
            .and_then(|m| m.get(key))
            .or_else(|| {
                self.messages
                    .get("en")
                    .and_then(|m| m.get(key))
            })
            .cloned()
            .unwrap_or_else(|| key.to_string())
    }
}

// 从请求中获取语言偏好
fn get_preferred_locale(req: &httprequest) -> string {
    req.headers()
        .get("accept-language")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.split(',').next())
        .and_then(|s| s.split('-').next())
        .unwrap_or("en")
        .to_string()
}

// 本地化的错误响应
fn localized_error_response(
    error: &apperror,
    locale: &str,
    catalog: &errormessagecatalog,
) -> errorresponse {
    let (message_key, context) = match error {
        apperror::validation { field, .. } => (
            "validation.required",
            some(json!({ "field": field })),
        ),
        apperror::unauthorized => (
            "auth.invalid_credentials",
            none,
        ),
        _ => (
            "error.general",
            none,
        ),
    };
    
    errorresponse {
        code: error.code(),
        message: catalog.get_message(message_key, locale),
        context,
    }
}

11.3 错误报告与反馈

use sentry::{clientoptions, hub};

struct errorreporter {
    sentry_hub: hub,
    slack_webhook: option<string>,
}

impl errorreporter {
    fn new(sentry_dsn: &str, slack_webhook: option<string>) -> self {
        let options = clientoptions {
            dsn: some(sentry_dsn.parse().unwrap()),
            ..default::default()
        };
        
        let hub = hub::new(some(sentry::init(options).into()));
        
        self {
            sentry_hub: hub,
            slack_webhook,
        }
    }
    
    async fn report_error(
        &self,
        error: &apperror,
        context: errorcontext,
    ) {
        // 发送到sentry
        self.sentry_hub.with_active(|| {
            sentry::capture_error(error);
            
            sentry::configure_scope(|scope| {
                scope.set_tag("environment", &context.environment);
                scope.set_tag("service", &context.service_name);
                scope.set_extra("trace_id", context.trace_id.clone().into());
                scope.set_extra("user_id", context.user_id.map(|id| id.into()).unwrap_or_default());
            });
        });
        
        // 关键错误发送到slack
        if error.is_critical() {
            if let some(webhook_url) = &self.slack_webhook {
                self.send_slack_alert(webhook_url, error, &context).await.ok();
            }
        }
    }
    
    async fn send_slack_alert(
        &self,
        webhook_url: &str,
        error: &apperror,
        context: &errorcontext,
    ) -> result<(), reqwest::error> {
        let message = json!({
            "text": format!("🚨 critical error in {}", context.service_name),
            "blocks": [
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": format!("*error:* {}\n*trace id:* {}\n*environment:* {}",
                            error,
                            context.trace_id,
                            context.environment)
                    }
                }
            ]
        });
        
        let client = reqwest::client::new();
        client.post(webhook_url)
            .json(&message)
            .send()
            .await?;
        
        ok(())
    }
}

struct errorcontext {
    trace_id: string,
    user_id: option<u32>,
    service_name: string,
    environment: string,
    timestamp: chrono::datetime<chrono::utc>,
}

impl apperror {
    fn is_critical(&self) -> bool {
        matches!(
            self,
            apperror::database(_)
                | apperror::externalserviceerror { .. }
                | apperror::datacorruption { .. }
        )
    }
}

第十二部分:总结与最佳实践

12.1 错误处理原则清单

// ✅ 好的做法
fn good_error_handling() -> result<data, apperror> {
    // 1. 使用具体的错误类型
    let data = fetch_data()
        .map_err(|e| apperror::datafetchfailed(e.to_string()))?;
    
    // 2. 添加上下文信息
    let parsed = parse_data(&data)
        .context("解析用户数据失败")?;
    
    // 3. 记录错误日志
    if let err(e) = validate(&parsed) {
        log::error!("数据验证失败: {}", e);
        return err(apperror::validationfailed(e.to_string()));
    }
    
    ok(parsed)
}

// ❌ 不好的做法
fn bad_error_handling() -> result<data, string> {
    // 1. 使用string作为错误类型
    let data = fetch_data()
        .map_err(|e| format!("错误: {}", e))?;
    
    // 2. 丢失错误上下文
    let parsed = parse_data(&data)
        .map_err(|_| "解析失败".to_string())?;
    
    // 3. 不记录错误
    validate(&parsed)
        .map_err(|e| e.to_string())?;
    
    ok(parsed)
}

12.2 关键要点总结

1. 类型安全的错误处理

  • 使用result<t, e>而不是panic或异常
  • 定义清晰的错误类型层次结构
  • 利用类型系统在编译时捕获错误

2. 错误传播与转换

  • 使用?操作符简化错误传播
  • 实现from trait进行错误类型转换
  • 使用thiserroranyhow简化错误定义

3. 上下文与可追溯性

  • 为错误添加丰富的上下文信息
  • 实现分布式追踪
  • 保留完整的错误链

4. 用户体验

  • 区分用户错误和系统错误
  • 提供清晰的错误消息和建议
  • 支持多语言错误消息

5. 可靠性保障

  • 实现重试机制
  • 使用断路器模式
  • 设计降级方案
  • 确保幂等性

6. 监控与告警

  • 实施结构化日志
  • 集成错误追踪系统
  • 设置关键指标告警
  • 定期审查错误趋势

7. 测试覆盖

  • 编写错误场景的单元测试
  • 实施混沌工程测试
  • 使用属性测试验证错误处理逻辑

8. 文档化

  • 文档化所有可能的错误类型
  • 提供错误代码参考
  • 包含错误处理示例

这份全面的指南涵盖了rust中错误处理的方方面面,从基础概念到高级模式,从实战案例到最佳实践。通过遵循这些原则和模式,你可以构建出健壮、可维护、用户友好的rust应用程序。

错误处理不仅仅是技术问题,更是关乎用户体验和系统可靠性的关键因素。在rust的帮助下,我们可以在编译时就捕获大量潜在错误,在运行时优雅地处理异常情况,最终交付高质量的软件产品。

到此这篇关于浅谈rust中错误处理与响应构建的文章就介绍到这了,更多相关rust错误处理与响应构建内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com