Skip to main content

scyph_core/
error.rs

1//! Standardized HTTP error handling for Scyph backends.
2//!
3//! This module provides [`AppError`], the canonical error envelope used across
4//! Scyph services. It follows the [RFC 7807 Problem Details](https://tools.ietf.org/html/rfc7807)
5//! format for HTTP APIs.
6//!
7//! # Architecture Overview
8//!
9//! Every Scyph handler returns `Result<T, AppError>`. When an error is returned, Axum calls
10//! [`AppError::into_response`](axum::response::IntoResponse::into_response) automatically,
11//! which serializes the error into the RFC 7807 JSON shape and sets the correct HTTP status code.
12//!
13//! The conversion chain is designed to be ergonomic:
14//!
15//! ```text
16//! Domain Error (e.g. sqlx::Error)
17//!      │  AppError::internal_from(e, "context")
18//!      ▼
19//! AppError::Internal { source, context }
20//!      │  IntoResponse
21//!      ▼
22//! HTTP 500 with opaque body:
23//! { "type": "https://httpstatuses.io/500",
24//!   "title": "INTERNAL_SERVER_ERROR",
25//!   "status": 500,
26//!   "detail": "An unexpected error occurred." }
27//! ```
28//!
29//! # Key Features
30//! - **RFC 7807 Compliance**: Serializes responses with `type`, `title`, `status`, and `detail`.
31//! - **Automatic Response Mapping**: Implements [`IntoResponse`](axum::response::IntoResponse) to easily return errors from Axum handlers.
32//! - **Security First**: Internal server errors mask sensitive implementation details from clients while logging full tracebacks.
33//! - **Structured Validation**: [`AppError::ValidationError`] carries per-field [`ErrorDetails`] for rich 422 responses.
34//! - **Custom Domain Errors**: [`AppError::Custom`] allows arbitrary status codes for domain-specific edge cases.
35//!
36//! # Examples
37//!
38//! Basic handler returning a typed error:
39//!
40//! ```rust
41//! use scyph_core::AppError;
42//! use axum::http::StatusCode;
43//!
44//! fn find_user(id: u64) -> Result<String, AppError> {
45//!     if id == 0 {
46//!         Err(AppError::NotFound("User not found".into()))
47//!     } else {
48//!         Ok("Alice".into())
49//!     }
50//! }
51//! ```
52//!
53//! Wrapping a library error with [`AppError::internal_from`]:
54//!
55//! ```rust,ignore
56//! use scyph_core::AppError;
57//!
58//! async fn fetch_user(pool: &sqlx::PgPool, id: uuid::Uuid) -> Result<String, AppError> {
59//!     sqlx::query_scalar::<_, String>("SELECT name FROM users WHERE id = $1")
60//!         .bind(id)
61//!         .fetch_one(pool)
62//!         .await
63//!         .map_err(|e| AppError::internal_from(e, "fetch_user: database query failed"))
64//! }
65//! ```
66//!
67//! Returning a [`AppError::ValidationError`] with per-field details:
68//!
69//! ```rust
70//! use scyph_core::{AppError, ErrorDetails};
71//!
72//! fn validate_registration(email: &str, age: u8) -> Result<(), AppError> {
73//!     let mut errors = Vec::new();
74//!     if !email.contains('@') {
75//!         errors.push(ErrorDetails {
76//!             code: "INVALID_EMAIL".into(),
77//!             message: "Must be a valid email address".into(),
78//!             field: Some("email".into()),
79//!         });
80//!     }
81//!     if age < 18 {
82//!         errors.push(ErrorDetails {
83//!             code: "UNDERAGE".into(),
84//!             message: "Must be at least 18 years old".into(),
85//!             field: Some("age".into()),
86//!         });
87//!     }
88//!     if errors.is_empty() {
89//!         Ok(())
90//!     } else {
91//!         Err(AppError::ValidationError {
92//!             message: "Registration validation failed".into(),
93//!             details: errors,
94//!         })
95//!     }
96//! }
97//! ```
98
99use axum::{
100    http::StatusCode,
101    response::{IntoResponse, Response},
102};
103use serde::{Deserialize, Serialize};
104use serde_json::json;
105use thiserror::Error;
106use tracing::error;
107
108/// Field-level detail for request payload validation or processing errors.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110pub struct ErrorDetails {
111    /// Machine-readable error code string (e.g., `"INVALID_EMAIL"`, `"REQUIRED"`).
112    pub code: String,
113    /// Human-readable description of the error.
114    pub message: String,
115    /// Optional field name or payload property path (e.g., `"email"`, `"pagination.limit"`).
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub field: Option<String>,
118}
119
120/// The canonical error type for all Scyph-based HTTP backends.
121///
122/// `AppError` maps domain and runtime errors into standardized HTTP status codes
123/// and RFC 7807 Problem Details JSON responses when returned from Axum handlers.
124///
125/// Internal errors ([`AppError::Internal`]) log the underlying source error using `tracing::error!`
126/// while returning an opaque message to clients, preventing internal leaks.
127#[derive(Debug, Error)]
128pub enum AppError {
129    /// 400 Bad Request — Malformed or invalid input that the client can fix.
130    #[error("Bad request: {0}")]
131    BadRequest(String),
132
133    /// 401 Unauthorized — Missing, invalid, or expired authentication credentials.
134    #[error("Unauthorized: {0}")]
135    Unauthorized(String),
136
137    /// 403 Forbidden — Authenticated entity lacks permission to access the resource.
138    #[error("Forbidden: {0}")]
139    Forbidden(String),
140
141    /// 404 Not Found — Requested resource could not be found.
142    #[error("Not found: {0}")]
143    NotFound(String),
144
145    /// 409 Conflict — Resource state conflict (e.g., duplicate email address on registration).
146    #[error("Conflict: {0}")]
147    Conflict(String),
148
149    /// 422 Unprocessable Entity — Request syntax is correct but validation failed.
150    #[error("Unprocessable: {0}")]
151    UnprocessableEntity(String),
152
153    /// 422 Unprocessable Entity — Structured request validation failure with field-level details.
154    #[error("Validation failed: {message}")]
155    ValidationError {
156        /// Summary validation failure message.
157        message: String,
158        /// List of field-level validation errors.
159        details: Vec<ErrorDetails>,
160    },
161
162    /// 402 Payment Required — Access requires payment or active subscription.
163    #[error("Payment required: {0}")]
164    PaymentRequired(String),
165
166    /// 429 Too Many Requests — Client has exceeded rate limit thresholds.
167    #[error("Too many requests: {0}")]
168    TooManyRequests(String),
169
170    /// 503 Service Unavailable — Server is temporarily overloaded or under maintenance.
171    #[error("Service unavailable: {0}")]
172    ServiceUnavailable(String),
173
174    /// 500 Internal Server Error — Unexpected internal failure.
175    ///
176    /// The full error context is logged via `tracing::error!`, but the client receives an
177    /// opaque generic detail message `"An unexpected error occurred."` to preserve security.
178    ///
179    /// # Security Masking
180    ///
181    /// This variant intentionally hides the underlying `source` error and `context` from HTTP
182    /// clients. Exposing database errors, stack traces, or internal service messages in API
183    /// responses is a common information-disclosure vulnerability (CWE-209). Instead:
184    ///
185    /// - The `source` and `context` are emitted to the structured tracing log at `ERROR` level,
186    ///   visible in your log aggregator (e.g., CloudWatch, Datadog).
187    /// - The HTTP response body always contains the fixed string `"An unexpected error occurred."`.
188    ///
189    /// This makes internal errors safe to return from any handler without risk of leaking
190    /// secrets, database schema details, or service internals to end users.
191    #[error("Internal server error")]
192    Internal {
193        /// The underlying source error causing the failure.
194        #[source]
195        source: Box<dyn std::error::Error + Send + Sync>,
196        /// Descriptive contextual summary of where/why the error occurred.
197        context: String,
198    },
199
200    /// Custom error variant for domain-specific HTTP responses.
201    #[error("{message}")]
202    Custom {
203        /// HTTP status code for the response.
204        status: StatusCode,
205        /// Machine-readable error code string (used in RFC 7807 `title`).
206        code: String,
207        /// Client-facing detail message.
208        message: String,
209    },
210}
211
212impl AppError {
213    /// Wraps any standard error (`std::error::Error`) into an internal server error variant ([`AppError::Internal`]).
214    ///
215    /// The underlying error will be logged internally via `tracing`, while the response detail sent
216    /// to the client is masked for security.
217    ///
218    /// # Arguments
219    ///
220    /// * `err` - The underlying source error.
221    /// * `ctx` - A human-readable context description explaining where the error occurred.
222    ///
223    /// # Security Note
224    ///
225    /// The `err` and `ctx` values are logged at `ERROR` level via `tracing` but are **never**
226    /// included in the HTTP response body. Clients always receive the opaque message
227    /// `"An unexpected error occurred."`.
228    ///
229    /// # Examples
230    ///
231    /// Wrapping a standard parse error:
232    ///
233    /// ```rust
234    /// use scyph_core::AppError;
235    ///
236    /// let parse_result: Result<i32, _> = "invalid".parse();
237    /// let app_err = parse_result.map_err(|e| AppError::internal_from(e, "Failed to parse integer"));
238    /// assert_eq!(app_err.unwrap_err().status(), axum::http::StatusCode::INTERNAL_SERVER_ERROR);
239    /// ```
240    ///
241    /// Wrapping a `sqlx` database error (requires `sqlx` in scope):
242    ///
243    /// ```rust,ignore
244    /// use scyph_core::AppError;
245    ///
246    /// async fn get_user(pool: &sqlx::PgPool, id: uuid::Uuid) -> Result<String, AppError> {
247    ///     sqlx::query_scalar::<_, String>("SELECT name FROM users WHERE id = $1")
248    ///         .bind(id)
249    ///         .fetch_one(pool)
250    ///         .await
251    ///         .map_err(|e| AppError::internal_from(e, "get_user: failed to query users table"))
252    /// }
253    /// ```
254    pub fn internal_from<E: std::error::Error + Send + Sync + 'static>(
255        err: E,
256        ctx: impl Into<String>,
257    ) -> Self {
258        Self::Internal {
259            source: Box::new(err),
260            context: ctx.into(),
261        }
262    }
263
264    /// Creates an internal server error ([`AppError::Internal`]) from a plain string message context
265    /// without a separate underlying source error.
266    ///
267    /// # Arguments
268    ///
269    /// * `ctx` - A message explaining the context of the internal failure.
270    ///
271    /// # Examples
272    ///
273    /// ```rust
274    /// use scyph_core::AppError;
275    ///
276    /// let err = AppError::internal("Database connection pool exhausted");
277    /// assert_eq!(err.status(), axum::http::StatusCode::INTERNAL_SERVER_ERROR);
278    /// ```
279    pub fn internal(ctx: impl Into<String>) -> Self {
280        let ctx = ctx.into();
281        struct StringError(String);
282        impl std::fmt::Debug for StringError {
283            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284                write!(f, "{}", self.0)
285            }
286        }
287        impl std::fmt::Display for StringError {
288            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289                write!(f, "{}", self.0)
290            }
291        }
292        impl std::error::Error for StringError {}
293        Self::Internal {
294            source: Box::new(StringError(ctx.clone())),
295            context: ctx,
296        }
297    }
298
299    /// Returns the HTTP status code associated with this error variant.
300    ///
301    /// # Examples
302    ///
303    /// ```rust
304    /// use scyph_core::AppError;
305    /// use axum::http::StatusCode;
306    ///
307    /// let err = AppError::NotFound("Item missing".into());
308    /// assert_eq!(err.status(), StatusCode::NOT_FOUND);
309    /// ```
310    pub fn status(&self) -> StatusCode {
311        match self {
312            Self::BadRequest(_) => StatusCode::BAD_REQUEST,
313            Self::Unauthorized(_) => StatusCode::UNAUTHORIZED,
314            Self::Forbidden(_) => StatusCode::FORBIDDEN,
315            Self::NotFound(_) => StatusCode::NOT_FOUND,
316            Self::Conflict(_) => StatusCode::CONFLICT,
317            Self::UnprocessableEntity(_) | Self::ValidationError { .. } => {
318                StatusCode::UNPROCESSABLE_ENTITY
319            }
320            Self::PaymentRequired(_) => StatusCode::PAYMENT_REQUIRED,
321            Self::TooManyRequests(_) => StatusCode::TOO_MANY_REQUESTS,
322            Self::ServiceUnavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
323            Self::Internal { .. } => StatusCode::INTERNAL_SERVER_ERROR,
324            Self::Custom { status, .. } => *status,
325        }
326    }
327
328    /// Returns a machine-readable string error code identifier (e.g., `"NOT_FOUND"`, `"UNAUTHORIZED"`).
329    ///
330    /// This string populates the `title` field in the RFC 7807 JSON error response.
331    ///
332    /// # Examples
333    ///
334    /// ```rust
335    /// use scyph_core::AppError;
336    ///
337    /// let err = AppError::Unauthorized("Invalid token".into());
338    /// assert_eq!(err.code(), "UNAUTHORIZED");
339    /// ```
340    pub fn code(&self) -> &str {
341        match self {
342            Self::BadRequest(_) => "BAD_REQUEST",
343            Self::Unauthorized(_) => "UNAUTHORIZED",
344            Self::Forbidden(_) => "FORBIDDEN",
345            Self::NotFound(_) => "NOT_FOUND",
346            Self::Conflict(_) => "CONFLICT",
347            Self::UnprocessableEntity(_) => "UNPROCESSABLE_ENTITY",
348            Self::ValidationError { .. } => "VALIDATION_ERROR",
349            Self::PaymentRequired(_) => "PAYMENT_REQUIRED",
350            Self::TooManyRequests(_) => "TOO_MANY_REQUESTS",
351            Self::ServiceUnavailable(_) => "SERVICE_UNAVAILABLE",
352            Self::Internal { .. } => "INTERNAL_SERVER_ERROR",
353            Self::Custom { code, .. } => code.as_str(),
354        }
355    }
356}
357
358impl IntoResponse for AppError {
359    fn into_response(self) -> Response {
360        if let Self::Internal {
361            ref source,
362            ref context,
363        } = self
364        {
365            error!(
366                error = %source,
367                context = %context,
368                "Internal server error"
369            );
370        }
371
372        let status = self.status();
373        let detail = match &self {
374            Self::Internal { .. } => "An unexpected error occurred.".to_string(),
375            Self::ValidationError { message, .. } => message.clone(),
376            other => other.to_string(),
377        };
378
379        let mut body = json!({
380            "type":   format!("https://httpstatuses.io/{}", status.as_u16()),
381            "title":  self.code(),
382            "status": status.as_u16(),
383            "detail": detail,
384        });
385
386        if let Self::ValidationError { details, .. } = &self
387            && let Some(obj) = body.as_object_mut()
388        {
389            obj.insert("details".to_string(), json!(details));
390        }
391
392        (status, axum::Json(body)).into_response()
393    }
394}