1use axum::{
2 http::StatusCode,
3 response::{IntoResponse, Response},
4 Json,
5};
6use serde_json::json;
7use std::collections::BTreeMap;
8
9pub type ValidationErrors = BTreeMap<String, Vec<String>>;
11
12pub type Result<T = ()> = std::result::Result<T, AppError>;
14
15#[derive(thiserror::Error)]
17pub enum AppError {
18 #[error("Resource not found")]
20 NotFound,
21 #[error("Unauthenticated")]
23 Unauthorized,
24 #[error("Forbidden")]
26 Forbidden,
27 #[error("Validation failed")]
29 Validation(ValidationErrors),
30 #[error("{0}")]
32 Conflict(String),
33 #[error("{0}")]
35 BadRequest(String),
36 #[error("Request body too large")]
38 PayloadTooLarge,
39 #[error("Content-Type must be application/json")]
41 UnsupportedMediaType,
42 #[error("Method not allowed")]
44 MethodNotAllowed,
45 #[error("Database operation failed")]
47 Database(#[from] sea_orm::DbErr),
48 #[error("Failed to connect to database: {}. Check DATABASE_URL and database availability.", connection_cause(.0))]
51 DatabaseConnection(#[source] sea_orm::DbErr),
52 #[error("Internal server error")]
54 Internal(#[from] anyhow::Error),
55 #[error("{0}")]
57 Configuration(String),
58 #[error("Could not start the HTTP server. Check APP_HOST, APP_PORT, and port availability.")]
60 Io(#[from] std::io::Error),
61}
62
63impl std::fmt::Debug for AppError {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 std::fmt::Display::fmt(self, f)
67 }
68}
69
70#[derive(Clone, Copy, Debug)]
72pub struct ErrorKind(pub &'static str);
73
74fn connection_cause(error: &sea_orm::DbErr) -> &'static str {
75 use sea_orm::{ConnAcquireErr, DbErr, RuntimeErr, SqlxError};
76 match error {
77 DbErr::ConnectionAcquire(ConnAcquireErr::Timeout) => "connection pool timed out",
78 DbErr::ConnectionAcquire(ConnAcquireErr::ConnectionClosed) => "connection pool closed",
79 DbErr::Conn(RuntimeErr::SqlxError(error)) => match error {
80 SqlxError::Io(e) => match e.kind() {
81 std::io::ErrorKind::ConnectionRefused => "connection refused",
82 std::io::ErrorKind::TimedOut => "connection timed out",
83 std::io::ErrorKind::PermissionDenied => "permission denied",
84 _ => "network or filesystem I/O failure",
85 },
86 SqlxError::Tls(_) => "TLS negotiation failed",
87 SqlxError::Configuration(_) => "invalid connection options",
88 SqlxError::Database(_) => "database rejected the connection",
89 SqlxError::PoolTimedOut => "connection pool timed out",
90 _ => "driver connection failure",
91 },
92 _ => "driver connection failure",
93 }
94}
95
96impl AppError {
97 pub fn kind(&self) -> &'static str {
99 match self {
100 Self::Database(_) | Self::DatabaseConnection(_) => "database",
101 Self::Internal(_) => "internal",
102 Self::Configuration(_) => "configuration",
103 Self::Io(_) => "io",
104 Self::Validation(_) => "validation",
105 _ => "request",
106 }
107 }
108
109 pub fn status(&self) -> StatusCode {
111 match self {
112 Self::NotFound => StatusCode::NOT_FOUND,
113 Self::Unauthorized => StatusCode::UNAUTHORIZED,
114 Self::Forbidden => StatusCode::FORBIDDEN,
115 Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
116 Self::Conflict(_) => StatusCode::CONFLICT,
117 Self::BadRequest(_) => StatusCode::BAD_REQUEST,
118 Self::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
119 Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
120 Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
121 _ => StatusCode::INTERNAL_SERVER_ERROR,
122 }
123 }
124}
125
126impl IntoResponse for AppError {
127 fn into_response(self) -> Response {
128 let status = self.status();
129 let body = if let Self::Validation(errors) = &self {
130 json!({ "message": "Validation failed", "errors": errors })
131 } else if status.is_server_error() {
132 json!({ "message": "Internal server error" })
133 } else {
134 json!({ "message": self.to_string() })
135 };
136 let mut response = (status, Json(body)).into_response();
137 response.extensions_mut().insert(ErrorKind(self.kind()));
138 response
139 }
140}