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 Internal(String),
42}
43
44impl IntoResponse for Error {
45 fn into_response(self) -> Response {
46 let (status, error_message) = match self {
47 Error::Config(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
48 Error::Io(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
49 Error::Serialization(_) => (StatusCode::BAD_REQUEST, self.to_string()),
50 Error::TomlParsing(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
51 Error::ServerStart(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
52 Error::Middleware(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
53 #[cfg(feature = "templates")]
54 Error::Template(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
55 #[cfg(feature = "jwt")]
56 Error::Jwt(_) => (StatusCode::UNAUTHORIZED, "认证失败".to_string()),
57 Error::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, self.to_string()),
58 };
59
60 let body = Json(json!({
61 "error": error_message,
62 "status": status.as_u16()
63 }));
64
65 (status, body).into_response()
66 }
67}
68
69pub type Result<T> = std::result::Result<T, Error>;