Skip to main content

capy_core/
error.rs

1use axum::{
2    http::StatusCode,
3    response::{IntoResponse, Response},
4    Json,
5};
6use serde::Serialize;
7use std::collections::BTreeMap;
8
9/// Field names (including dotted nested paths) mapped to validation messages.
10pub type ValidationErrors = BTreeMap<String, Vec<String>>;
11
12/// JSON wire envelope for Capy's standardized errors. It never carries native causes.
13#[derive(Clone, Debug, Serialize, schemars::JsonSchema)]
14pub struct ApiErrorResponse {
15    /// Safe public message.
16    pub message: String,
17    /// Field validation errors, present only for validation failures.
18    #[serde(skip_serializing_if = "Option::is_none")]
19    #[schemars(with = "ValidationErrors")]
20    pub errors: Option<ValidationErrors>,
21}
22
23/// The result type used by application handlers and startup.
24pub type Result<T = ()> = std::result::Result<T, AppError>;
25
26/// Errors with predictable HTTP statuses and safe public messages.
27#[derive(thiserror::Error)]
28pub enum AppError {
29    /// The resource does not exist.
30    #[error("Resource not found")]
31    NotFound,
32    /// Authentication is required.
33    #[error("Unauthenticated")]
34    Unauthorized,
35    /// The operation is forbidden.
36    #[error("Forbidden")]
37    Forbidden,
38    /// Field validation failed.
39    #[error("Validation failed")]
40    Validation(ValidationErrors),
41    /// A conflict message safe to send to clients.
42    #[error("{0}")]
43    Conflict(String),
44    /// A malformed request message safe to send to clients.
45    #[error("{0}")]
46    BadRequest(String),
47    /// The payload exceeds Axum's body limit.
48    #[error("Request body too large")]
49    PayloadTooLarge,
50    /// JSON requires an appropriate content type.
51    #[error("Content-Type must be application/json")]
52    UnsupportedMediaType,
53    /// No handler accepts this request method.
54    #[error("Method not allowed")]
55    MethodNotAllowed,
56    /// The process-local abuse limit has been reached.
57    #[error("Too many requests; try again later")]
58    TooManyRequests,
59    /// A native database error; its details are never returned over HTTP.
60    #[error("Database operation failed")]
61    Database(#[from] sea_orm::DbErr),
62    /// Database initialization failed; the native cause is retained for inspection.
63    /// Display/Debug use a safe category rather than driver text or connection URLs.
64    #[error("Failed to connect to database: {}. Check DATABASE_URL and database availability.", connection_cause(.0))]
65    DatabaseConnection(#[source] sea_orm::DbErr),
66    /// An internal error; its details are never returned over HTTP.
67    #[error("Internal server error")]
68    Internal(#[from] anyhow::Error),
69    /// A safe, actionable startup diagnostic.
70    #[error("{0}")]
71    Configuration(String),
72    /// An operating system error during startup.
73    #[error("Could not start the HTTP server. Check APP_HOST, APP_PORT, and port availability.")]
74    Io(#[from] std::io::Error),
75}
76
77// Rust's main prints Debug on failure. Keep that output safe as well.
78impl std::fmt::Debug for AppError {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        std::fmt::Display::fmt(self, f)
81    }
82}
83
84/// Safe error category carried on an HTTP response for request diagnostics.
85#[derive(Clone, Copy, Debug)]
86pub struct ErrorKind(pub &'static str);
87
88fn connection_cause(error: &sea_orm::DbErr) -> &'static str {
89    use sea_orm::{ConnAcquireErr, DbErr, RuntimeErr, SqlxError};
90    match error {
91        DbErr::ConnectionAcquire(ConnAcquireErr::Timeout) => "connection pool timed out",
92        DbErr::ConnectionAcquire(ConnAcquireErr::ConnectionClosed) => "connection pool closed",
93        DbErr::Conn(RuntimeErr::SqlxError(error)) => match error {
94            SqlxError::Io(e) => match e.kind() {
95                std::io::ErrorKind::ConnectionRefused => "connection refused",
96                std::io::ErrorKind::TimedOut => "connection timed out",
97                std::io::ErrorKind::PermissionDenied => "permission denied",
98                _ => "network or filesystem I/O failure",
99            },
100            SqlxError::Tls(_) => "TLS negotiation failed",
101            SqlxError::Configuration(_) => "invalid connection options",
102            SqlxError::Database(_) => "database rejected the connection",
103            SqlxError::PoolTimedOut => "connection pool timed out",
104            _ => "driver connection failure",
105        },
106        _ => "driver connection failure",
107    }
108}
109
110impl AppError {
111    /// Normalize native JSON rejections without reflecting payloads or parse internals.
112    pub fn from_json_rejection(error: axum::extract::rejection::JsonRejection) -> Self {
113        match error.status() {
114            StatusCode::PAYLOAD_TOO_LARGE => Self::PayloadTooLarge,
115            StatusCode::UNSUPPORTED_MEDIA_TYPE => Self::UnsupportedMediaType,
116            StatusCode::UNPROCESSABLE_ENTITY => Self::Validation(
117                [(
118                    "body".into(),
119                    vec!["The JSON body has missing or invalid fields.".into()],
120                )]
121                .into(),
122            ),
123            _ => Self::BadRequest("Malformed JSON body".into()),
124        }
125    }
126
127    /// Broad diagnostic category, safe to log without driver messages or input data.
128    pub fn kind(&self) -> &'static str {
129        match self {
130            Self::Database(_) | Self::DatabaseConnection(_) => "database",
131            Self::Internal(_) => "internal",
132            Self::Configuration(_) => "configuration",
133            Self::Io(_) => "io",
134            Self::Validation(_) => "validation",
135            _ => "request",
136        }
137    }
138
139    /// The public HTTP status associated with this error.
140    pub fn status(&self) -> StatusCode {
141        match self {
142            Self::NotFound => StatusCode::NOT_FOUND,
143            Self::Unauthorized => StatusCode::UNAUTHORIZED,
144            Self::Forbidden => StatusCode::FORBIDDEN,
145            Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
146            Self::Conflict(_) => StatusCode::CONFLICT,
147            Self::BadRequest(_) => StatusCode::BAD_REQUEST,
148            Self::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,
149            Self::UnsupportedMediaType => StatusCode::UNSUPPORTED_MEDIA_TYPE,
150            Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
151            Self::TooManyRequests => StatusCode::TOO_MANY_REQUESTS,
152            _ => StatusCode::INTERNAL_SERVER_ERROR,
153        }
154    }
155}
156
157impl IntoResponse for AppError {
158    fn into_response(self) -> Response {
159        let status = self.status();
160        let body = if let Self::Validation(errors) = &self {
161            ApiErrorResponse {
162                message: "Validation failed".into(),
163                errors: Some(errors.clone()),
164            }
165        } else if status.is_server_error() {
166            ApiErrorResponse {
167                message: "Internal server error".into(),
168                errors: None,
169            }
170        } else {
171            ApiErrorResponse {
172                message: self.to_string(),
173                errors: None,
174            }
175        };
176        let mut response = (status, Json(body)).into_response();
177        response.extensions_mut().insert(ErrorKind(self.kind()));
178        response
179    }
180}