Skip to main content

moonclient/
error.rs

1//! Domain error models, failure representations, and error conversion mechanics.
2//!
3//! Encapsulates transport-level network faults, JSON parsing discrepancies, filesystem I/O issues,
4//! and remote HTTP error status codes into a unified, strongly typed [`MoonError`] enum.
5//!
6//! ### Public API Stability Guarantee
7//!
8//! Volatile third-party error types (such as [`reqwest::Error`](https://docs.rs/reqwest/latest/reqwest/struct.Error.html)
9//! or [`reqwest_middleware::Error`](https://docs.rs/reqwest-middleware/latest/reqwest_middleware/struct.Error.html))
10//! are boxed or coerced into string representations at the boundary. This guarantees that major version
11//! bumps in underlying network crates do not induce breaking changes in downstream consumer code.
12//!
13//! ### Dynamic Localization (i18n)
14//!
15//! All error variants integrate with Project Fluent via the [`tr!`](crate::tr) macro, formatting
16//! localized diagnostic descriptions dynamically according to the active execution context
17//! (Tokio Task-Local or process-wide locale).
18//!
19//! ### Quick Example
20//!
21//! ```rust
22//! use moonclient::{MoonError, Result};
23//!
24//! fn handle_failure(result: Result<()>) {
25//!     match result {
26//!         Ok(()) => println!("Transaction completed successfully!"),
27//!         Err(MoonError::ApiError { code, message }) => {
28//!             eprintln!("Remote server error HTTP {}: {}", code, message);
29//!         }
30//!         Err(MoonError::ResponseDecode { error_message, raw }) => {
31//!             eprintln!("Schema mismatch: {}\nRaw payload: {}", error_message, raw);
32//!         }
33//!         Err(err) => eprintln!("Network transaction failed: {}", err),
34//!     }
35//! }
36//! ```
37
38use serde::Deserialize;
39use std::collections::HashMap;
40use thiserror::Error;
41
42/// Primary error type for the `moonclient` core framework.
43///
44/// Encapsulates transport-level network faults, parsing discrepancies, I/O failures,
45/// and API validation errors. External dependency types are converted into stable internal
46/// representations, guaranteeing public API stability.
47#[derive(Error, Debug)]
48pub enum MoonError {
49    /// Failure originated within the internal middleware pipeline.
50    ///
51    /// Typically triggered by retry policy exhaustion, rate limiters, or tracing failures.
52    #[error("{}", crate::tr!("err-middleware", "error" => .0))]
53    Middleware(String),
54
55    /// Transport-level network failure.
56    ///
57    /// Occurs during connection drops, DNS resolution failures, timeouts,
58    /// or physical transport disconnects.
59    #[error("{}", crate::tr!("err-network", "error" => .0))]
60    Network(String),
61
62    /// Serialization or deserialization failure.
63    ///
64    /// Caused by payload schema mismatches against expected serde structures.
65    #[error("{}", crate::tr!("err-parse", "error" => .0))]
66    Parse(#[from] serde_json::Error),
67
68    /// Filesystem input/output error.
69    ///
70    /// Occurs when failing to read or persist session caches, disk stores,
71    /// or encountering file permission violations.
72    #[error("{}", crate::tr!("err-io", "error" => .0.to_string()))]
73    Io(std::io::Error),
74
75    /// Specific remote API validation failure (HTTP 422 Unprocessable Entity).
76    ///
77    /// Carries detailed per-field validation violation maps or flat message vectors.
78    #[error("{}", crate::tr!("err-api-validation", "error" => .0.to_string()))]
79    ApiValidation(ApiErrors),
80
81    /// Standard HTTP error status returned by the remote server (HTTP 4xx, 5xx).
82    ///
83    /// Used for non-422 status codes (e.g., 404 Not Found, 502 Bad Gateway).
84    #[error("{}", crate::tr!("err-api-error", "code" => code, "message" => message))]
85    ApiError {
86        /// HTTP status code returned by the server (e.g., 403, 500).
87        code: u16,
88        /// Raw response body or status code explanation.
89        message: String,
90    },
91
92    /// Network client configuration error.
93    ///
94    /// Triggered by invalid rate limiter parameters, malformed base URLs,
95    /// or missing required state components.
96    #[error("{}", crate::tr!("err-config", "error" => .0))]
97    Config(String),
98
99    /// Response deserialization failure with bounded raw payload preservation for debugging.
100    ///
101    /// Prevents raw payload loss during deserialization crashes, allowing developers
102    /// to inspect the unparseable payload fragment in logs.
103    #[error("{}", crate::tr!("err-response-decode", "error" => error_message, "raw" => raw))]
104    ResponseDecode {
105        /// Textual error description provided by [`serde_json`](https://docs.rs/serde_json).
106        error_message: String,
107        /// Raw textual response body that triggered the crash (buffer-bounded to avoid OOM).
108        raw: String,
109    },
110
111    /// Local client authorization failure.
112    ///
113    /// Triggered when attempting to invoke authenticated endpoints without an active session in memory.
114    #[error("{}", crate::tr!("err-unauthorized", "error" => .0))]
115    Unauthorized(String),
116
117    /// Local client-side parameter validation error.
118    ///
119    /// Preemptively prevents dispatching obviously invalid requests, saving bandwidth and rate limits.
120    #[error("{}", crate::tr!("err-validation-error", "error" => .0))]
121    ValidationError(String),
122
123    /// Unforeseen internal system failure.
124    #[error("{}", crate::tr!("err-unknown"))]
125    Unknown,
126}
127
128// =============================================================================
129// 🔄 AUTOMATIC ERROR CONVERSIONS
130// =============================================================================
131
132impl From<reqwest_middleware::Error> for MoonError {
133    /// Converts a [`reqwest_middleware::Error`](https://docs.rs/reqwest-middleware/latest/reqwest_middleware/struct.Error.html)
134    /// into a stable [`MoonError::Middleware`].
135    ///
136    /// # Arguments
137    ///
138    /// * `err` ([`reqwest_middleware::Error`](https://docs.rs/reqwest-middleware/latest/reqwest_middleware/struct.Error.html)) — Middleware pipeline error.
139    ///
140    /// # Returns
141    ///
142    /// A standardized [`MoonError::Middleware`] variant.
143    fn from(err: reqwest_middleware::Error) -> Self {
144        MoonError::Middleware(err.to_string())
145    }
146}
147
148impl From<reqwest::Error> for MoonError {
149    /// Converts a [`reqwest::Error`](https://docs.rs/reqwest/latest/reqwest/struct.Error.html)
150    /// into a stable [`MoonError::Network`].
151    ///
152    /// # Arguments
153    ///
154    /// * `err` ([`reqwest::Error`](https://docs.rs/reqwest/latest/reqwest/struct.Error.html)) — Transport or protocol error from reqwest.
155    ///
156    /// # Returns
157    ///
158    /// A standardized [`MoonError::Network`] variant.
159    fn from(err: reqwest::Error) -> Self {
160        MoonError::Network(err.to_string())
161    }
162}
163
164impl From<std::io::Error> for MoonError {
165    /// Converts an [`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html)
166    /// into a [`MoonError::Io`].
167    ///
168    /// # Arguments
169    ///
170    /// * `err` ([`std::io::Error`](https://doc.rust-lang.org/std/io/struct.Error.html)) — Low-level filesystem or stream I/O error.
171    ///
172    /// # Returns
173    ///
174    /// A standardized [`MoonError::Io`] variant.
175    fn from(err: std::io::Error) -> Self {
176        MoonError::Io(err)
177    }
178}
179
180// =============================================================================
181// 📝 REMOTE API VALIDATION MODELS (HTTP 422)
182// =============================================================================
183
184/// Representation variants for remote API validation failures (HTTP 422 Unprocessable Entity).
185///
186/// Uses `#[serde(untagged)]` to automatically handle both structured per-field error dictionaries
187/// and flat arrays of server validation warnings.
188///
189/// # Example
190///
191/// ```rust
192/// use moonclient::error::ApiErrors;
193///
194/// // 1. Flat message list
195/// let flat: ApiErrors = serde_json::from_str(r#"["Invalid email format", "Password too short"]"#).unwrap();
196/// println!("Flat errors: {}", flat);
197///
198/// // 2. Per-field validation map
199/// let fields: ApiErrors = serde_json::from_str(r#"{"email": ["Already taken"], "age": ["Must be 18+"]}"#).unwrap();
200/// println!("Field errors: {}", fields);
201/// ```
202#[derive(Debug, Deserialize, Clone, PartialEq)]
203#[serde(untagged)]
204pub enum ApiErrors {
205    /// Validation errors mapped to specific request fields (e.g. `{"errors": {"email": ["Already taken"]}}`).
206    Fields(HashMap<String, Vec<String>>),
207    /// Generic backend error messages (e.g. `{"errors": ["Access denied by rule"]}`).
208    Messages(Vec<String>),
209}
210
211impl std::fmt::Display for ApiErrors {
212    /// Formats the API errors into a human-readable comma-separated summary.
213    ///
214    /// # Arguments
215    ///
216    /// * `f` ([`&mut std::fmt::Formatter<'_>`](https://doc.rust-lang.org/std/fmt/struct.Formatter.html)) — Output formatter stream.
217    ///
218    /// # Returns
219    ///
220    /// Returns `std::fmt::Result` indicating successful formatting.
221    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222        match self {
223            ApiErrors::Fields(map) => {
224                let mut first = true;
225                for (field, msgs) in map {
226                    if !first {
227                        write!(f, ", ")?;
228                    }
229                    write!(f, "{}: {}", field, msgs.join("; "))?;
230                    first = false;
231                }
232                Ok(())
233            }
234            ApiErrors::Messages(vec) => {
235                write!(f, "{}", vec.join("; "))
236            }
237        }
238    }
239}
240
241/// Helper structure for deserializing remote API validation error envelopes (HTTP 422).
242///
243/// Many modern REST backends wrap 422 validation failures inside an `{"errors": ...}` JSON object.
244#[derive(Debug, Deserialize)]
245pub struct ApiErrorResponse {
246    /// Structured validation error payload body.
247    pub errors: ApiErrors,
248}
249
250/// Ergonomic type alias for [`std::result::Result`] specialized over [`MoonError`].
251///
252/// Commonly used across all client methods and pipelines for concise signatures.
253///
254/// # Example
255///
256/// ```rust
257/// use moonclient::{MoonError, Result};
258///
259/// fn check_quota(limit: u32) -> Result<()> {
260///     if limit > 100 {
261///         return Err(MoonError::ValidationError("Quota exceeded limit of 100".to_string()));
262///     }
263///     Ok(())
264/// }
265/// ```
266pub type Result<T> = std::result::Result<T, MoonError>;