1use crate::{Response, StatusCode};
8use serde::Serialize;
9use thiserror::Error;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
13pub enum ErrorCode {
14 NotFound,
15 BadRequest,
16 Unauthorized,
17 Forbidden,
18 Conflict,
19 #[serde(rename = "VALIDATION_ERROR")]
20 Validation,
21 #[serde(rename = "RATE_LIMIT_EXCEEDED")]
22 RateLimitExceeded,
23 #[serde(rename = "DATABASE_ERROR")]
24 Database,
25 #[serde(rename = "INTERNAL_ERROR")]
26 Internal,
27}
28
29impl ErrorCode {
30 pub const fn as_str(self) -> &'static str {
31 match self {
32 Self::NotFound => "NOT_FOUND",
33 Self::BadRequest => "BAD_REQUEST",
34 Self::Unauthorized => "UNAUTHORIZED",
35 Self::Forbidden => "FORBIDDEN",
36 Self::Conflict => "CONFLICT",
37 Self::Validation => "VALIDATION_ERROR",
38 Self::RateLimitExceeded => "RATE_LIMIT_EXCEEDED",
39 Self::Database => "DATABASE_ERROR",
40 Self::Internal => "INTERNAL_ERROR",
41 }
42 }
43}
44
45#[derive(Debug, Serialize)]
47pub struct ErrorDocument {
48 pub error: ErrorDetails,
49}
50
51#[derive(Debug, Serialize)]
52pub struct ErrorDetails {
53 pub code: ErrorCode,
54 pub message: String,
55 pub status: u16,
56 #[serde(skip_serializing_if = "Option::is_none")]
57 pub request_id: Option<String>,
58}
59
60#[derive(Debug, Error)]
62pub enum AppError {
63 #[error("Not found: {0}")]
64 NotFound(String),
65
66 #[error("Bad request: {0}")]
67 BadRequest(String),
68
69 #[error("Unauthorized: {0}")]
70 Unauthorized(String),
71
72 #[error("Forbidden: {0}")]
73 Forbidden(String),
74
75 #[error("Conflict: {0}")]
76 Conflict(String),
77
78 #[error("Validation error: {0}")]
79 Validation(String),
80
81 #[error("Rate limit exceeded")]
82 RateLimitExceeded,
83
84 #[error("Database error: {0}")]
85 Database(String),
86
87 #[error("Internal server error: {0}")]
88 Internal(String),
89}
90
91impl AppError {
92 pub const fn code(&self) -> ErrorCode {
94 match self {
95 Self::NotFound(_) => ErrorCode::NotFound,
96 Self::BadRequest(_) => ErrorCode::BadRequest,
97 Self::Unauthorized(_) => ErrorCode::Unauthorized,
98 Self::Forbidden(_) => ErrorCode::Forbidden,
99 Self::Conflict(_) => ErrorCode::Conflict,
100 Self::Validation(_) => ErrorCode::Validation,
101 Self::RateLimitExceeded => ErrorCode::RateLimitExceeded,
102 Self::Database(_) => ErrorCode::Database,
103 Self::Internal(_) => ErrorCode::Internal,
104 }
105 }
106
107 pub const fn status_code(&self) -> StatusCode {
109 match self {
110 Self::NotFound(_) => StatusCode::NOT_FOUND,
111 Self::BadRequest(_) | Self::Validation(_) => StatusCode::BAD_REQUEST,
112 Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
113 Self::Forbidden(_) => StatusCode::FORBIDDEN,
114 Self::Conflict(_) => StatusCode::CONFLICT,
115 Self::RateLimitExceeded => StatusCode::TOO_MANY_REQUESTS,
116 Self::Database(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
117 }
118 }
119
120 pub fn public_message(&self) -> String {
122 match self {
123 Self::NotFound(message)
124 | Self::BadRequest(message)
125 | Self::Unauthorized(message)
126 | Self::Forbidden(message)
127 | Self::Conflict(message)
128 | Self::Validation(message) => message.clone(),
129 Self::RateLimitExceeded => "Too many requests".to_string(),
130 Self::Database(_) => "A database error occurred".to_string(),
131 Self::Internal(_) => "An internal server error occurred".to_string(),
132 }
133 }
134
135 pub fn into_response(self) -> Response {
137 self.into_response_with_request_id(None)
138 }
139
140 pub fn into_response_with_request_id(self, request_id: Option<&str>) -> Response {
142 self.response_with_request_id(request_id)
143 }
144
145 pub fn response_with_request_id(&self, request_id: Option<&str>) -> Response {
147 let status = self.status_code();
148 let request_id = request_id.map(str::to_owned);
149 let document = ErrorDocument {
150 error: ErrorDetails {
151 code: self.code(),
152 message: self.public_message(),
153 status: status.as_u16(),
154 request_id: request_id.clone(),
155 },
156 };
157
158 let mut response = Response::new()
159 .status(status)
160 .header("Content-Type", "application/json")
161 .json(&document)
162 .expect("structured error serialization should not fail");
163 if let Some(request_id) = request_id {
164 response = response.header("X-Request-ID", &request_id);
165 }
166 response
167 }
168}
169
170impl From<sqlx::Error> for AppError {
171 fn from(err: sqlx::Error) -> Self {
172 match err {
173 sqlx::Error::RowNotFound => Self::NotFound("Resource not found".to_string()),
174 _ => Self::Database(err.to_string()),
175 }
176 }
177}
178
179impl From<std::io::Error> for AppError {
180 fn from(err: std::io::Error) -> Self {
181 Self::Internal(err.to_string())
182 }
183}
184
185impl From<serde_json::Error> for AppError {
186 fn from(err: serde_json::Error) -> Self {
187 Self::BadRequest(format!("JSON error: {}", err))
188 }
189}
190
191impl From<Box<dyn std::error::Error + Send + Sync>> for AppError {
192 fn from(err: Box<dyn std::error::Error + Send + Sync>) -> Self {
193 Self::Internal(err.to_string())
194 }
195}
196
197pub type AppResult<T> = Result<T, AppError>;
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203 use hyper::body::to_bytes;
204
205 #[tokio::test]
206 async fn structured_error_contains_stable_metadata_and_request_id() {
207 let response = AppError::Validation("email is invalid".to_string())
208 .into_response_with_request_id(Some("req-123"));
209 let body = to_bytes(response.body).await.unwrap();
210 let document: serde_json::Value = serde_json::from_slice(&body).unwrap();
211
212 assert_eq!(response.status, StatusCode::BAD_REQUEST);
213 assert_eq!(
214 response.headers.get("X-Request-ID"),
215 Some(&"req-123".to_string())
216 );
217 assert_eq!(document["error"]["code"], "VALIDATION_ERROR");
218 assert_eq!(document["error"]["status"], 400);
219 assert_eq!(document["error"]["message"], "email is invalid");
220 assert_eq!(document["error"]["request_id"], "req-123");
221 }
222
223 #[tokio::test]
224 async fn internal_details_are_not_exposed() {
225 let response = AppError::Internal("database password leaked".to_string()).into_response();
226 let body = to_bytes(response.body).await.unwrap();
227 let document: serde_json::Value = serde_json::from_slice(&body).unwrap();
228
229 assert_eq!(response.status, StatusCode::INTERNAL_SERVER_ERROR);
230 assert_eq!(document["error"]["code"], "INTERNAL_ERROR");
231 assert_eq!(
232 document["error"]["message"],
233 "An internal server error occurred"
234 );
235 assert!(!document.to_string().contains("database password leaked"));
236 }
237}