1use axum::{
4 http::StatusCode,
5 response::{IntoResponse, Response},
6 Json,
7};
8use serde_json::json;
9use thiserror::Error;
10
11#[derive(Error, Debug)]
13pub enum Error {
14 #[error("配置错误: {0}")]
15 Config(String),
16
17 #[error("IO 错误: {0}")]
18 Io(#[from] std::io::Error),
19
20 #[error("序列化错误: {0}")]
21 Serialization(#[from] serde_json::Error),
22
23 #[error("TOML 解析错误: {0}")]
24 TomlParsing(#[from] toml::de::Error),
25
26 #[error("服务器启动失败: {0}")]
27 ServerStart(String),
28
29 #[error("中间件错误: {0}")]
30 Middleware(String),
31
32 #[error("模板错误: {0}")]
33 #[cfg(feature = "templates")]
34 Template(#[from] tera::Error),
35
36 #[error("JWT 错误: {0}")]
37 #[cfg(feature = "jwt")]
38 Jwt(#[from] jsonwebtoken::errors::Error),
39
40 #[error("数据库错误: {0}")]
41 Database(String),
42
43 #[error("内部错误: {0}")]
44 Internal(String),
45}
46
47impl IntoResponse for Error {
48 fn into_response(self) -> Response {
49 let (status, error_message) = match self {
50 Error::Config(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
51 Error::Io(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
52 Error::Serialization(_) => (StatusCode::BAD_REQUEST, self.to_string()),
53 Error::TomlParsing(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
54 Error::ServerStart(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
55 Error::Middleware(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
56 #[cfg(feature = "templates")]
57 Error::Template(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
58 #[cfg(feature = "jwt")]
59 Error::Jwt(_) => (StatusCode::UNAUTHORIZED, "认证失败".to_string()),
60 Error::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
61 Error::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
62 };
63
64 let body = Json(json!({
65 "error": error_message,
66 "status": status.as_u16()
67 }));
68
69 (status, body).into_response()
70 }
71}
72
73pub type Result<T> = std::result::Result<T, Error>;