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 from_json_rejection(error: axum::extract::rejection::JsonRejection) -> Self {
99 match error.status() {
100 StatusCode::PAYLOAD_TOO_LARGE => Self::PayloadTooLarge,
101 StatusCode::UNSUPPORTED_MEDIA_TYPE => Self::UnsupportedMediaType,
102 StatusCode::UNPROCESSABLE_ENTITY => Self::Validation(
103 [(
104 "body".into(),
105 vec!["The JSON body has missing or invalid fields.".into()],
106 )]
107 .into(),
108 ),
109 _ => Self::BadRequest("Malformed JSON body".into()),
110 }
111 }
112
113 pub fn kind(&self) -> &'static str {
115 match self {
116 Self::Database(_) | Self::DatabaseConnection(_) => "database",
117 Self::Internal(_) => "internal",
118 Self::Configuration(_) => "configuration",
119 Self::Io(_) => "io",
120 Self::Validation(_) => "validation",
121 _ => "request",
122 }
123 }
124
125 pub fn status(&self) -> StatusCode {
127 match self {
128 Self::NotFound => StatusCode::NOT_FOUND,
129 Self::Unauthorized => StatusCode::UNAUTHORIZED,
130 Self::Forbidden => StatusCode::FORBIDDEN,
131 Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
132 Self::Conflict(_) => StatusCode::CONFLICT,
133 Self::BadRequest(_) => StatusCode::BAD_REQUEST,
134 Self::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
135 Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
136 Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
137 _ => StatusCode::INTERNAL_SERVER_ERROR,
138 }
139 }
140}
141
142impl IntoResponse for AppError {
143 fn into_response(self) -> Response {
144 let status = self.status();
145 let body = if let Self::Validation(errors) = &self {
146 json!({ "message": "Validation failed", "errors": errors })
147 } else if status.is_server_error() {
148 json!({ "message": "Internal server error" })
149 } else {
150 json!({ "message": self.to_string() })
151 };
152 let mut response = (status, Json(body)).into_response();
153 response.extensions_mut().insert(ErrorKind(self.kind()));
154 response
155 }
156}