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