# ADR-005: 统一错误处理策略 / Unified Error Handling Strategy ## 状态 / Status **Accepted** **日期 / Date**: 2024-01-01 ## 背景 / Context 平台需要统一的错误处理机制,确保错误信息对用户友好,同时保留足够的调试信息。 The platform needs a unified error handling mechanism that provides user-friendly error messages while retaining sufficient debugging information. ## 决策 / Decision 使用 **AppError 枚举 + AppResult 类型别名** 作为统一错误处理策略。 Use **AppError enum + AppResult type alias** as the unified error handling strategy. ## 考虑的方案 / Considered Options 1. **自定义枚举 (AppError)** — 类型安全、可扩展 2. **anyhow** — 简单但类型信息丢失 3. **thiserror + 手动实现** — 灵活但工作量大 ## 后果 / Consequences ### 正面 / Positive - 类型安全的错误处理 / Type-safe error handling - 统一的错误响应格式 / Unified error response format - 便于错误分类和监控 / Easy error classification and monitoring - 与 actix-web 集成良好 / Good integration with actix-web ### 负面 / Negative - 需要维护错误枚举 / Need to maintain error enum - 新增错误类型需要更新枚举 / New error types require enum updates ## 实现细节 / Implementation Details ```rust // AppError 定义 #[derive(Debug, thiserror::Error)] pub enum AppError { #[error("User not found")] UserNotFound, #[error("Invalid password")] InvalidPassword, #[error("Database error: {0}")] Database(#[from] sqlx::Error), // ... } // AppResult 类型别名 pub type AppResult = Result; ``` ## 错误码映射 / Error Code Mapping | Postgres Code | 含义 | HTTP Status | |---|---|---| | 23505 | 唯一约束违反 | 409 Conflict | | 23503 | 外键约束违反 | 400 Bad Request | | 23514 | 检查约束违反 | 400 Bad Request | | 23502 | 非空约束违反 | 400 Bad Request | | 23P01 | 排他约束违反 | 409 Conflict |