Skip to main content

capy_core/
error.rs

1use axum::{
2    http::StatusCode,
3    response::{IntoResponse, Response},
4    Json,
5};
6use serde_json::json;
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/// The result type used by application handlers and startup.
13pub type Result<T = ()> = std::result::Result<T, AppError>;
14
15/// Errors with predictable HTTP statuses and safe public messages.
16#[derive(thiserror::Error)]
17pub enum AppError {
18    /// The resource does not exist.
19    #[error("Resource not found")]
20    NotFound,
21    /// Authentication is required.
22    #[error("Unauthenticated")]
23    Unauthorized,
24    /// The operation is forbidden.
25    #[error("Forbidden")]
26    Forbidden,
27    /// Field validation failed.
28    #[error("Validation failed")]
29    Validation(ValidationErrors),
30    /// A conflict message safe to send to clients.
31    #[error("{0}")]
32    Conflict(String),
33    /// A malformed request message safe to send to clients.
34    #[error("{0}")]
35    BadRequest(String),
36    /// The payload exceeds Axum's body limit.
37    #[error("Request body too large")]
38    PayloadTooLarge,
39    /// JSON requires an appropriate content type.
40    #[error("Content-Type must be application/json")]
41    UnsupportedMediaType,
42    /// No handler accepts this request method.
43    #[error("Method not allowed")]
44    MethodNotAllowed,
45    /// A native database error; its details are never returned over HTTP.
46    #[error("Database operation failed")]
47    Database(#[from] sea_orm::DbErr),
48    /// Database initialization failed; the native cause is retained for inspection.
49    /// Display/Debug use a safe category rather than driver text or connection URLs.
50    #[error("Failed to connect to database: {}. Check DATABASE_URL and database availability.", connection_cause(.0))]
51    DatabaseConnection(#[source] sea_orm::DbErr),
52    /// An internal error; its details are never returned over HTTP.
53    #[error("Internal server error")]
54    Internal(#[from] anyhow::Error),
55    /// A safe, actionable startup diagnostic.
56    #[error("{0}")]
57    Configuration(String),
58    /// An operating system error during startup.
59    #[error("Could not start the HTTP server. Check APP_HOST, APP_PORT, and port availability.")]
60    Io(#[from] std::io::Error),
61}
62
63// Rust's main prints Debug on failure. Keep that output safe as well.
64impl 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/// Safe error category carried on an HTTP response for request diagnostics.
71#[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    /// Broad diagnostic category, safe to log without driver messages or input data.
98    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    /// The public HTTP status associated with this error.
110    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}