1use axum::{
2 http::StatusCode,
3 response::{IntoResponse, Response},
4 Json,
5};
6use serde::Serialize;
7use std::collections::BTreeMap;
8
9pub type ValidationErrors = BTreeMap<String, Vec<String>>;
11
12#[derive(Clone, Debug, Serialize, schemars::JsonSchema)]
14pub struct ApiErrorResponse {
15 #[serde(skip_serializing_if = "Option::is_none")]
17 pub code: Option<String>,
18 pub message: String,
20 #[serde(skip_serializing_if = "Option::is_none")]
22 #[schemars(with = "ValidationErrors")]
23 pub errors: Option<ValidationErrors>,
24}
25
26pub type Result<T = ()> = std::result::Result<T, AppError>;
28
29#[derive(thiserror::Error)]
31pub enum AppError {
32 #[error("Resource not found")]
34 NotFound,
35 #[error("Unauthenticated")]
37 Unauthorized,
38 #[error("Forbidden")]
40 Forbidden,
41 #[error("Validation failed")]
43 Validation(ValidationErrors),
44 #[error("{0}")]
46 Conflict(String),
47 #[error("{0}")]
49 BadRequest(String),
50 #[error("Request body too large")]
52 PayloadTooLarge,
53 #[error("Content-Type must be application/json")]
55 UnsupportedMediaType,
56 #[error("Method not allowed")]
58 MethodNotAllowed,
59 #[error("Too many requests; try again later")]
61 TooManyRequests,
62 #[error("Service temporarily unavailable")]
65 AuthCapacity,
66 #[error("Service temporarily unavailable")]
68 ClientIdentityUnavailable,
69 #[error("Internal server error")]
71 Lifecycle,
72 #[error("{0}")]
74 Rejected(#[from] crate::EventRejection),
75 #[error("Database operation failed")]
77 Database(#[from] sea_orm::DbErr),
78 #[error("Failed to connect to database: {}. Check DATABASE_URL and database availability.", connection_cause(.0))]
81 DatabaseConnection(#[source] sea_orm::DbErr),
82 #[error("Internal server error")]
84 Internal(#[from] anyhow::Error),
85 #[error("{0}")]
87 Configuration(String),
88 #[error("Could not start the HTTP server. Check APP_HOST, APP_PORT, and port availability.")]
90 Io(#[from] std::io::Error),
91}
92
93impl std::fmt::Debug for AppError {
95 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96 std::fmt::Display::fmt(self, f)
97 }
98}
99
100#[derive(Clone, Copy, Debug)]
102pub struct ErrorKind(pub &'static str);
103
104fn connection_cause(error: &sea_orm::DbErr) -> &'static str {
105 use sea_orm::{ConnAcquireErr, DbErr, RuntimeErr, SqlxError};
106 match error {
107 DbErr::ConnectionAcquire(ConnAcquireErr::Timeout) => "connection pool timed out",
108 DbErr::ConnectionAcquire(ConnAcquireErr::ConnectionClosed) => "connection pool closed",
109 DbErr::Conn(RuntimeErr::SqlxError(error)) => match error {
110 SqlxError::Io(e) => match e.kind() {
111 std::io::ErrorKind::ConnectionRefused => "connection refused",
112 std::io::ErrorKind::TimedOut => "connection timed out",
113 std::io::ErrorKind::PermissionDenied => "permission denied",
114 _ => "network or filesystem I/O failure",
115 },
116 SqlxError::Tls(_) => "TLS negotiation failed",
117 SqlxError::Configuration(_) => "invalid connection options",
118 SqlxError::Database(_) => "database rejected the connection",
119 SqlxError::PoolTimedOut => "connection pool timed out",
120 _ => "driver connection failure",
121 },
122 _ => "driver connection failure",
123 }
124}
125
126impl AppError {
127 pub fn from_json_rejection(error: axum::extract::rejection::JsonRejection) -> Self {
129 match error.status() {
130 StatusCode::PAYLOAD_TOO_LARGE => Self::PayloadTooLarge,
131 StatusCode::UNSUPPORTED_MEDIA_TYPE => Self::UnsupportedMediaType,
132 StatusCode::UNPROCESSABLE_ENTITY => Self::Validation(
133 [(
134 "body".into(),
135 vec!["The JSON body has missing or invalid fields.".into()],
136 )]
137 .into(),
138 ),
139 _ => Self::BadRequest("Malformed JSON body".into()),
140 }
141 }
142
143 pub fn kind(&self) -> &'static str {
145 match self {
146 Self::Lifecycle => "lifecycle",
147 Self::Rejected(_) => "application_rejection",
148 Self::AuthCapacity => "auth_capacity",
149 Self::ClientIdentityUnavailable => "client_identity",
150 Self::Database(_) | Self::DatabaseConnection(_) => "database",
151 Self::Internal(_) => "internal",
152 Self::Configuration(_) => "configuration",
153 Self::Io(_) => "io",
154 Self::Validation(_) => "validation",
155 _ => "request",
156 }
157 }
158
159 pub fn status(&self) -> StatusCode {
161 match self {
162 Self::Rejected(problem) => problem.status(),
163 Self::NotFound => StatusCode::NOT_FOUND,
164 Self::Unauthorized => StatusCode::UNAUTHORIZED,
165 Self::Forbidden => StatusCode::FORBIDDEN,
166 Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
167 Self::Conflict(_) => StatusCode::CONFLICT,
168 Self::BadRequest(_) => StatusCode::BAD_REQUEST,
169 Self::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
170 Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
171 Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
172 Self::TooManyRequests => StatusCode::TOO_MANY_REQUESTS,
173 Self::AuthCapacity | Self::ClientIdentityUnavailable => StatusCode::SERVICE_UNAVAILABLE,
174 _ => StatusCode::INTERNAL_SERVER_ERROR,
175 }
176 }
177}
178
179impl IntoResponse for AppError {
180 fn into_response(self) -> Response {
181 let status = self.status();
182 let body = if let Self::Rejected(problem) = &self {
183 ApiErrorResponse {
184 code: Some(problem.code().into()),
185 message: problem.to_string(),
186 errors: match problem {
187 crate::EventRejection::Validation { errors, .. } => Some(errors.clone()),
188 _ => None,
189 },
190 }
191 } else if let Self::Validation(errors) = &self {
192 ApiErrorResponse {
193 code: None,
194 message: "Validation failed".into(),
195 errors: Some(errors.clone()),
196 }
197 } else if status.is_server_error() {
198 ApiErrorResponse {
199 code: None,
200 message: if status == StatusCode::SERVICE_UNAVAILABLE {
201 "Service temporarily unavailable"
202 } else {
203 "Internal server error"
204 }
205 .into(),
206 errors: None,
207 }
208 } else {
209 ApiErrorResponse {
210 code: None,
211 message: self.to_string(),
212 errors: None,
213 }
214 };
215 let mut response = (status, Json(body)).into_response();
216 response.extensions_mut().insert(ErrorKind(self.kind()));
217 response
218 }
219}