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("Database operation failed")]
58 Database(#[from] sea_orm::DbErr),
59 #[error("Failed to connect to database: {}. Check DATABASE_URL and database availability.", connection_cause(.0))]
62 DatabaseConnection(#[source] sea_orm::DbErr),
63 #[error("Internal server error")]
65 Internal(#[from] anyhow::Error),
66 #[error("{0}")]
68 Configuration(String),
69 #[error("Could not start the HTTP server. Check APP_HOST, APP_PORT, and port availability.")]
71 Io(#[from] std::io::Error),
72}
73
74impl std::fmt::Debug for AppError {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 std::fmt::Display::fmt(self, f)
78 }
79}
80
81#[derive(Clone, Copy, Debug)]
83pub struct ErrorKind(pub &'static str);
84
85fn connection_cause(error: &sea_orm::DbErr) -> &'static str {
86 use sea_orm::{ConnAcquireErr, DbErr, RuntimeErr, SqlxError};
87 match error {
88 DbErr::ConnectionAcquire(ConnAcquireErr::Timeout) => "connection pool timed out",
89 DbErr::ConnectionAcquire(ConnAcquireErr::ConnectionClosed) => "connection pool closed",
90 DbErr::Conn(RuntimeErr::SqlxError(error)) => match error {
91 SqlxError::Io(e) => match e.kind() {
92 std::io::ErrorKind::ConnectionRefused => "connection refused",
93 std::io::ErrorKind::TimedOut => "connection timed out",
94 std::io::ErrorKind::PermissionDenied => "permission denied",
95 _ => "network or filesystem I/O failure",
96 },
97 SqlxError::Tls(_) => "TLS negotiation failed",
98 SqlxError::Configuration(_) => "invalid connection options",
99 SqlxError::Database(_) => "database rejected the connection",
100 SqlxError::PoolTimedOut => "connection pool timed out",
101 _ => "driver connection failure",
102 },
103 _ => "driver connection failure",
104 }
105}
106
107impl AppError {
108 pub fn from_json_rejection(error: axum::extract::rejection::JsonRejection) -> Self {
110 match error.status() {
111 StatusCode::PAYLOAD_TOO_LARGE => Self::PayloadTooLarge,
112 StatusCode::UNSUPPORTED_MEDIA_TYPE => Self::UnsupportedMediaType,
113 StatusCode::UNPROCESSABLE_ENTITY => Self::Validation(
114 [(
115 "body".into(),
116 vec!["The JSON body has missing or invalid fields.".into()],
117 )]
118 .into(),
119 ),
120 _ => Self::BadRequest("Malformed JSON body".into()),
121 }
122 }
123
124 pub fn kind(&self) -> &'static str {
126 match self {
127 Self::Database(_) | Self::DatabaseConnection(_) => "database",
128 Self::Internal(_) => "internal",
129 Self::Configuration(_) => "configuration",
130 Self::Io(_) => "io",
131 Self::Validation(_) => "validation",
132 _ => "request",
133 }
134 }
135
136 pub fn status(&self) -> StatusCode {
138 match self {
139 Self::NotFound => StatusCode::NOT_FOUND,
140 Self::Unauthorized => StatusCode::UNAUTHORIZED,
141 Self::Forbidden => StatusCode::FORBIDDEN,
142 Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
143 Self::Conflict(_) => StatusCode::CONFLICT,
144 Self::BadRequest(_) => StatusCode::BAD_REQUEST,
145 Self::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
146 Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
147 Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
148 _ => StatusCode::INTERNAL_SERVER_ERROR,
149 }
150 }
151}
152
153impl IntoResponse for AppError {
154 fn into_response(self) -> Response {
155 let status = self.status();
156 let body = if let Self::Validation(errors) = &self {
157 ApiErrorResponse {
158 message: "Validation failed".into(),
159 errors: Some(errors.clone()),
160 }
161 } else if status.is_server_error() {
162 ApiErrorResponse {
163 message: "Internal server error".into(),
164 errors: None,
165 }
166 } else {
167 ApiErrorResponse {
168 message: self.to_string(),
169 errors: None,
170 }
171 };
172 let mut response = (status, Json(body)).into_response();
173 response.extensions_mut().insert(ErrorKind(self.kind()));
174 response
175 }
176}