1use thiserror::Error;
6
7#[derive(Error, Debug)]
9pub enum OpenApiError {
10 #[error("JSON处理错误: {0}")]
12 Json(#[from] serde_json::Error),
13
14 #[error("Silent框架错误: {0}")]
16 Silent(#[from] silent::SilentError),
17
18 #[error("OpenAPI文档生成错误: {0}")]
20 OpenApiGeneration(String),
21
22 #[error("Swagger UI资源错误: {0}")]
24 SwaggerUi(String),
25
26 #[error("HTTP错误: {0}")]
28 Http(#[from] http::Error),
29
30 #[error("路径匹配错误: {path}")]
32 PathMismatch { path: String },
33
34 #[error("资源未找到: {resource}")]
36 ResourceNotFound { resource: String },
37
38 #[error("配置错误: {message}")]
40 Configuration { message: String },
41}
42
43pub type Result<T> = std::result::Result<T, OpenApiError>;
45
46impl OpenApiError {
47 pub fn openapi_generation<S: Into<String>>(message: S) -> Self {
49 Self::OpenApiGeneration(message.into())
50 }
51
52 pub fn swagger_ui<S: Into<String>>(message: S) -> Self {
54 Self::SwaggerUi(message.into())
55 }
56
57 pub fn configuration<S: Into<String>>(message: S) -> Self {
59 Self::Configuration {
60 message: message.into(),
61 }
62 }
63
64 pub fn resource_not_found<S: Into<String>>(resource: S) -> Self {
66 Self::ResourceNotFound {
67 resource: resource.into(),
68 }
69 }
70}
71
72impl From<OpenApiError> for silent::Response {
73 fn from(error: OpenApiError) -> Self {
74 use silent::StatusCode;
75
76 let (status, message) = match &error {
77 OpenApiError::ResourceNotFound { .. } => (StatusCode::NOT_FOUND, error.to_string()),
78 OpenApiError::PathMismatch { .. } => (StatusCode::NOT_FOUND, error.to_string()),
79 OpenApiError::Configuration { .. } => {
80 (StatusCode::INTERNAL_SERVER_ERROR, error.to_string())
81 }
82 _ => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()),
83 };
84
85 let mut response = silent::Response::empty();
86 response.set_status(status);
87 response.set_body(message.into());
88 response
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn test_error_creation() {
98 let error = OpenApiError::openapi_generation("测试错误");
99 assert!(error.to_string().contains("测试错误"));
100
101 let error = OpenApiError::resource_not_found("swagger.json");
102 assert!(error.to_string().contains("swagger.json"));
103 }
104
105 #[test]
106 fn test_error_conversion_to_response() {
107 let error = OpenApiError::resource_not_found("test.json");
108 let _response: silent::Response = error.into();
109 }
111}