Skip to main content

neocrates_response/
error.rs

1use std::{fmt::Display, panic::Location};
2
3use axum::{
4    Json,
5    http::StatusCode,
6    response::{IntoResponse, Response},
7};
8use serde::Serialize;
9use thiserror::Error;
10use validator::ValidationErrors;
11
12// 1. Common success status codes (2xx):
13// - 200 for general success responses (GET/PUT/PATCH)
14// - 201 for successful creation (POST)
15// - 204 for no content responses (DELETE)
16// - 202 for asynchronous task acceptance
17
18// 2. Redirect status codes (3xx):
19// - 301 for permanent resource relocation
20// - 302 for temporary redirects
21// - 304 for not modified, use cache
22// - 307/308 for redirects preserving HTTP method
23
24// 3. Client error status codes (4xx):
25// - 400 for malformed requests (parameter errors)
26// - 401 for unauthenticated requests (not logged in)
27// - 403 for unauthorized access (logged in but insufficient permissions)
28// - 404 for resource not found
29// - 409 for resource conflicts (duplicate creation)
30
31// 4. Server error status codes (5xx):
32// - 500 for internal server errors (unexpected exceptions)
33// - 502 for gateway errors (upstream service exceptions)
34// - 503 for service unavailable (maintenance or overload)
35// - 504 for gateway timeout (upstream service timeout)
36
37// 5. Special purpose status codes:
38// - 422 for business rule validation failures
39// - 429 for request rate limits
40// - 418 for fun easter egg responses
41
42// 6. RESTful API common scenarios:
43// - GET success returns 200
44// - POST creation success returns 201
45// - PUT/PATCH update success returns 200
46// - DELETE success returns 204
47
48// 7. Error handling principles:
49// - Use 4xx series for client errors
50// - Use 5xx series for server errors
51// - Provide clear error messages and handling suggestions
52// - Maintain uniform error response format
53
54// 8. Status code selection criteria:
55// - Prioritize semantically matching status codes
56// - Maintain consistency within the application
57// - Avoid uncommon status codes
58// - Consider client compatibility
59
60// 9. Cache-related status codes:
61// - 304 used with ETag/Last-Modified
62// - Cache control for GET requests
63// - Use caching to improve performance
64
65// 10. Security-related status codes:
66// - 401 for authentication failures
67// - 403 for permission verification failures
68// - 429 for security rate limiting
69// - 451 for legally prohibited access
70
71pub type AppResult<T> = std::result::Result<T, AppError>;
72
73// System error code enumeration
74#[derive(Error, Debug)]
75pub enum AppError {
76    // Client errors (4xx)
77    #[error("{0}")]
78    ValidationError(String), // Parameter validation failure
79    #[error("Unauthorized")]
80    Unauthorized, // Not logged in or invalid token
81    #[error("Token Expired")]
82    TokenExpired,
83    #[error("Forbidden")]
84    Forbidden, // Insufficient permissions
85    #[error("Resource not found: {0}")]
86    NotFound(String), // Resource doesn't exist
87    #[error("Request conflict: {0}")]
88    Conflict(String), // Resource conflict
89    #[error("{0}")]
90    ClientError(String), // General client error
91    #[error("{0}")]
92    ClientDataError(String), // General client data error
93
94    #[error("Business rule validation failed: {0}")]
95    UnprocessableEntity(String), // 422: Business rule validation
96    #[error("Rate limit exceeded: {0}")]
97    RateLimit(String), // 429: Rate limit exceeded
98    #[error("{0}")]
99    EasterEgg(String), // 418: Fun easter egg responses
100
101    // Server errors (5xx)
102    #[error("Database error: {0}")]
103    DbError(String), // Database error
104    #[error("Redis error: {0}")]
105    RedisError(String), // Redis error
106    #[error("Message queue error: {0}")]
107    MqError(String), // Message queue error
108    #[error("External service error: {0}")]
109    ExternalError(String), // External service call error
110    #[error("Internal server error")]
111    Internal(String), // Other internal errors
112
113    #[error("{1}")]
114    DataError(u32, String), // Custom business code and error message
115
116    #[error("{0}")]
117    JsonError(String), // JSON serialization error
118}
119
120// API response structure
121#[derive(Serialize)]
122pub struct ApiResponse<T> {
123    pub code: u32,       // Business status code
124    pub message: String, // Error message
125    pub data: Option<T>, // Response data
126}
127
128// Error code and HTTP status code mapping
129/// HTTP status code and business code mappings for application errors
130impl AppError {
131    // HTTP status code constants
132    const HTTP_BAD_REQUEST: StatusCode = StatusCode::BAD_REQUEST; // 400
133    const HTTP_UNAUTHORIZED: StatusCode = StatusCode::UNAUTHORIZED; // 401
134    const HTTP_FORBIDDEN: StatusCode = StatusCode::FORBIDDEN; // 403
135    const HTTP_NOT_FOUND: StatusCode = StatusCode::NOT_FOUND; // 404
136    const HTTP_CONFLICT: StatusCode = StatusCode::CONFLICT; // 409
137    const HTTP_UNPROCESSABLE_ENTITY: StatusCode = StatusCode::UNPROCESSABLE_ENTITY; // 422
138    const HTTP_TOO_MANY_REQUESTS: StatusCode = StatusCode::TOO_MANY_REQUESTS; // 429
139    const HTTP_IM_A_TEAPOT: StatusCode = StatusCode::IM_A_TEAPOT; // 418
140    const EXPECTATION_FAILED: StatusCode = StatusCode::EXPECTATION_FAILED; // 417
141    const HTTP_INTERNAL_ERROR: StatusCode = StatusCode::INTERNAL_SERVER_ERROR; // 500
142
143    // Business error code constants
144    const BIZ_VALIDATION_ERROR: u32 = 400001;
145    const BIZ_UNAUTHORIZED: u32 = 400002;
146    const BIZ_FORBIDDEN: u32 = 400003;
147    const BIZ_NOT_FOUND: u32 = 400004;
148    const BIZ_CONFLICT: u32 = 400005;
149    const BIZ_CLIENT_ERROR: u32 = 400006;
150    const BIZ_DATA_ERROR: u32 = 400007;
151    const BIZ_TOKEN_EXPIRED: u32 = 400008;
152    const BIZ_DB_ERROR: u32 = 500001;
153    const BIZ_REDIS_ERROR: u32 = 500002;
154    const BIZ_MQ_ERROR: u32 = 500003;
155    const BIZ_EXTERNAL_ERROR: u32 = 500004;
156    const BIZ_INTERNAL_ERROR: u32 = 500000;
157    const BIZ_UNPROCESSABLE_ENTITY: u32 = 400100; // Business validation errors
158    const BIZ_RATE_LIMIT: u32 = 400101; // Rate limiting errors
159    const BIZ_EASTER_EGG: u32 = 400102; // Easter egg responses
160
161    // Business data errors - Expanded categories
162    // 410000-410099: Data existence errors
163    pub const BIZ_DATA_EXISTS: u32 = 410000; // Data already exists
164    pub const BIZ_DATA_DUPLICATE: u32 = 410001; // Duplicate entry found
165    pub const BIZ_DATA_NOT_FOUND: u32 = 410002; // Data not found/doesn't exist
166    pub const BIZ_DATA_DELETED: u32 = 410003; // Data has been deleted
167    pub const BIZ_DATA_ARCHIVED: u32 = 410004; // Data is archived
168    pub const BIZ_DATA_OUTDATED: u32 = 410005; // Data version is outdated
169
170    // 410100-410199: JSON serialization errors
171    pub const BIZ_JSON_ERROR: u32 = 410100; // JSON serialization error
172
173    /// Maps application errors to HTTP status codes
174    pub fn status_code(&self) -> StatusCode {
175        match self {
176            // 4xx Client Errors
177            Self::ValidationError(_) => Self::HTTP_BAD_REQUEST,
178            Self::Unauthorized => Self::HTTP_UNAUTHORIZED,
179            Self::TokenExpired => Self::HTTP_UNAUTHORIZED,
180            Self::Forbidden => Self::HTTP_FORBIDDEN,
181            Self::NotFound(_) => Self::HTTP_NOT_FOUND,
182            Self::Conflict(_) => Self::HTTP_CONFLICT,
183            Self::UnprocessableEntity(_) => Self::HTTP_UNPROCESSABLE_ENTITY,
184            Self::RateLimit(_) => Self::HTTP_TOO_MANY_REQUESTS,
185            Self::EasterEgg(_) => Self::HTTP_IM_A_TEAPOT,
186            Self::Internal(_) => Self::HTTP_INTERNAL_ERROR,
187            Self::ClientError(_) => Self::EXPECTATION_FAILED,
188            Self::DataError(_, _) => Self::HTTP_CONFLICT, // All data errors use HTTP 409
189            // 4xx HTTP_BAD_REQUEST - Return 400 for all
190            _ => Self::HTTP_BAD_REQUEST,
191        }
192    }
193
194    /// Maps application errors to business error codes
195    pub fn business_code(&self) -> u32 {
196        match self {
197            // 4xx Client Errors
198            Self::ValidationError(_) => Self::BIZ_VALIDATION_ERROR,
199            Self::Unauthorized => Self::BIZ_UNAUTHORIZED,
200            Self::TokenExpired => Self::BIZ_TOKEN_EXPIRED,
201            Self::Forbidden => Self::BIZ_FORBIDDEN,
202            Self::NotFound(_) => Self::BIZ_NOT_FOUND,
203            Self::Conflict(_) => Self::BIZ_CONFLICT,
204            Self::UnprocessableEntity(_) => Self::BIZ_UNPROCESSABLE_ENTITY,
205            Self::RateLimit(_) => Self::BIZ_RATE_LIMIT,
206            Self::EasterEgg(_) => Self::BIZ_EASTER_EGG,
207            Self::ClientError(_) => Self::BIZ_CLIENT_ERROR,
208            Self::ClientDataError(_) => Self::BIZ_DATA_ERROR,
209            Self::DataError(code, _) => *code, // Use the custom business code from DataError
210            // 5xx Server Errors
211            Self::DbError(_) => Self::BIZ_DB_ERROR,
212            Self::RedisError(_) => Self::BIZ_REDIS_ERROR,
213            Self::MqError(_) => Self::BIZ_MQ_ERROR,
214            Self::ExternalError(_) => Self::BIZ_EXTERNAL_ERROR,
215            Self::Internal(_) => Self::BIZ_INTERNAL_ERROR,
216            // Business data errors
217            // Self::DataExtis(_) => Self::BIZ_DATA_EXTIS,
218            //
219            Self::JsonError(_) => Self::BIZ_JSON_ERROR,
220        }
221    }
222
223    /// Returns a user-friendly error message
224    pub fn message(&self) -> String {
225        match self {
226            Self::UnprocessableEntity(msg) => msg.to_string(),
227            Self::RateLimit(msg) => format!("Rate limit exceeded: {}", msg),
228            Self::EasterEgg(msg) => format!("Easter egg: {}", msg),
229            Self::ValidationError(msg) => msg.to_string(),
230            Self::Unauthorized => "Unauthorized access".to_string(),
231            Self::TokenExpired => "Token expired".to_string(),
232            Self::Forbidden => "Access forbidden".to_string(),
233            Self::NotFound(msg) => msg.to_string(),
234            Self::Conflict(msg) => msg.to_string(),
235            Self::DbError(e) => format!("Database error: {}", e),
236            Self::RedisError(e) => format!("Cache error: {}", e),
237            Self::MqError(e) => format!("Message queue error: {}", e),
238            Self::ExternalError(e) => format!("External service error: {}", e),
239            Self::Internal(e) => format!("Internal server error: {}", e),
240            Self::ClientError(msg) => msg.to_string(),
241            Self::ClientDataError(msg) => msg.to_string(),
242            Self::DataError(_, msg) => msg.to_string(),
243            Self::JsonError(msg) => format!("JSON serialization error: {}", msg),
244        }
245    }
246}
247
248// Implement response conversion
249impl IntoResponse for AppError {
250    fn into_response(self) -> Response {
251        let status = self.status_code();
252        let response = ApiResponse {
253            code: self.business_code(),
254            message: self.to_string(),
255            data: None::<()>,
256        };
257        // Log the response
258        tracing::error!(
259            "...App Error...: code:{:?} message:{:?} self:{:?}",
260            response.code,
261            response.message,
262            self
263        );
264        (status, Json(response)).into_response()
265    }
266}
267
268impl From<ValidationErrors> for AppError {
269    fn from(err: ValidationErrors) -> Self {
270        tracing::warn!("Parameter validation failed: {:?}", err);
271        let message = err
272            .field_errors()
273            .iter()
274            .map(|(field, errors)| {
275                let error_messages: Vec<String> = errors
276                    .iter()
277                    .filter_map(|error| error.message.as_ref().map(|m| m.to_string()))
278                    .collect();
279                format!("{}: {}", field, error_messages.join(", "))
280            })
281            .collect::<Vec<String>>()
282            .join("; ");
283
284        AppError::ValidationError(format!("Parameter validation failed: {}", message))
285    }
286}
287
288impl From<diesel::result::Error> for AppError {
289    fn from(err: diesel::result::Error) -> Self {
290        tracing::error!("Database error: {}", err);
291        AppError::DbError(err.to_string())
292    }
293}
294
295impl From<deadpool_diesel::PoolError> for AppError {
296    fn from(err: deadpool_diesel::PoolError) -> Self {
297        tracing::error!("Deadpool_diesel Database error: {}", err);
298        AppError::DbError(err.to_string())
299    }
300}
301
302#[track_caller]
303pub fn msg_with_location<M: Display>(msg: M) -> String {
304    let loc = Location::caller();
305    format!("{}:{} {}", loc.file(), loc.line(), msg)
306}
307
308impl AppError {
309    #[track_caller]
310    pub fn client_here<M: Display>(msg: M) -> Self {
311        AppError::ClientError(msg_with_location(msg))
312    }
313
314    #[track_caller]
315    pub fn data_here<M: Display>(msg: M) -> Self {
316        AppError::ClientDataError(msg_with_location(msg))
317    }
318
319    #[track_caller]
320    pub fn conflict_here<M: Display>(msg: M) -> Self {
321        AppError::Conflict(msg_with_location(msg))
322    }
323
324    #[track_caller]
325    pub fn not_found_here<M: Display>(msg: M) -> Self {
326        AppError::NotFound(msg_with_location(msg))
327    }
328}
329
330pub trait AppResultExt<T, E> {
331    #[track_caller]
332    fn client_context(self) -> AppResult<T>
333    where
334        E: Display;
335
336    #[track_caller]
337    fn context_msg(self, msg: impl Into<String>) -> AppResult<T>
338    where
339        E: Display;
340}
341
342impl<T, E> AppResultExt<T, E> for Result<T, E> {
343    #[track_caller]
344    fn client_context(self) -> AppResult<T>
345    where
346        E: Display,
347    {
348        self.map_err(|e| AppError::client_here(e))
349    }
350
351    #[track_caller]
352    fn context_msg(self, msg: impl Into<String>) -> AppResult<T>
353    where
354        E: Display,
355    {
356        self.map_err(|e| AppError::client_here(format!("{} - {}", msg.into(), e)))
357    }
358}
359
360// let chat_model: ChatModel = AgentChatService::get_agent_and_model(&app_state, pctx.aid)
361//     .await
362//     .map_err(AppError::client_here)?; // 等价于 |e| AppError::client_here(e)
363
364// use crate::response::error::AppResultExt;
365
366// let chat_model = AgentChatService::get_agent_and_model(&app_state, pctx.aid)
367//     .await
368//     .client_context()?; // 自动附带调用行号
369
370// impl Error for diesel::result::Error {
371//     fn as_infra_error(&self) -> InfraError {
372//         match self {
373//             diesel::result::Error::NotFound => InfraError::NotFound,
374//             _ => InfraError::InternalServerError,
375//         }
376//     }
377// }
378
379// impl Error for deadpool_diesel::PoolError {
380//     fn as_infra_error(&self) -> InfraError {
381//         InfraError::InternalServerError
382//     }
383// }
384
385// #[cfg(test)]
386// mod tests {
387//     use super::*;
388
389//     #[test]
390//     fn test_error_handling_examples() {
391//         // 1. Business validation error (422)
392//         let validation_error = AppError::UnprocessableEntity("用户名已存在".to_string());
393//         assert_eq!(
394//             validation_error.status_code(),
395//             StatusCode::UNPROCESSABLE_ENTITY
396//         );
397//         assert_eq!(validation_error.message(), "用户名已存在");
398
399//         // 2. Rate limiting error (429)
400//         let rate_limit_error = AppError::RateLimit("每分钟最多请求60次".to_string());
401//         assert_eq!(
402//             rate_limit_error.status_code(),
403//             StatusCode::TOO_MANY_REQUESTS
404//         );
405//         assert_eq!(
406//             rate_limit_error.message(),
407//             "请求频率超限: 每分钟最多请求60次"
408//         );
409
410//         // 3. Easter egg response (418)
411//         let easter_egg = AppError::EasterEgg("我是一个可爱的茶壶".to_string());
412//         assert_eq!(easter_egg.status_code(), StatusCode::IM_A_TEAPOT);
413//         assert_eq!(easter_egg.message(), "趣味彩蛋: 我是一个可爱的茶壶");
414//     }
415
416//     // 实际使用示例
417//     async fn example_handler() -> Result<String, AppError> {
418//         // 1. 业务规则验证
419//         if !is_valid_business_rule() {
420//             return Err(AppError::UnprocessableEntity(
421//                 "输入数据不符合业务规则".to_string(),
422//             ));
423//         }
424
425//         // 2. 频率限制检查
426//         if is_rate_limited() {
427//             return Err(AppError::RateLimit("请稍后再试".to_string()));
428//         }
429
430//         // 3. 趣味彩蛋
431//         if is_april_first() {
432//             return Err(AppError::EasterEgg("今天是愚人节!".to_string()));
433//         }
434
435//         Ok("处理成功".to_string())
436//     }
437
438//     // Mock functions
439//     fn is_valid_business_rule() -> bool {
440//         true
441//     }
442//     fn is_rate_limited() -> bool {
443//         false
444//     }
445//     fn is_april_first() -> bool {
446//         false
447//     }
448// }