Skip to main content

use_api_error/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7/// Error returned when API primitive text or labels are invalid.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10    /// The supplied value was empty after trimming.
11    Empty,
12    /// The supplied value used syntax this crate rejects.
13    Invalid,
14    /// The supplied label was not recognized.
15    Unknown,
16}
17
18impl fmt::Display for ApiPrimitiveError {
19    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20        match self {
21            Self::Empty => formatter.write_str("API primitive value cannot be empty"),
22            Self::Invalid => formatter.write_str("invalid API primitive value"),
23            Self::Unknown => formatter.write_str("unknown API primitive label"),
24        }
25    }
26}
27
28impl Error for ApiPrimitiveError {}
29
30fn validate_api_text(value: &str) -> Result<&str, ApiPrimitiveError> {
31    let trimmed = value.trim();
32    if trimmed.is_empty() {
33        return Err(ApiPrimitiveError::Empty);
34    }
35    if trimmed.chars().any(char::is_control) {
36        return Err(ApiPrimitiveError::Invalid);
37    }
38    Ok(trimmed)
39}
40
41macro_rules! text_newtype {
42    ($name:ident) => {
43        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44        pub struct $name(String);
45
46        impl $name {
47            /// Creates validated text metadata.
48            ///
49            /// # Errors
50            ///
51            /// Returns [ApiPrimitiveError] when the value is empty or contains control characters.
52            pub fn new(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
53                validate_api_text(value.as_ref()).map(|value| Self(value.to_owned()))
54            }
55
56            /// Parses validated text metadata.
57            ///
58            /// # Errors
59            ///
60            /// Returns [ApiPrimitiveError] when validation fails.
61            pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62                Self::new(value)
63            }
64
65            /// Returns the stored text.
66            #[must_use]
67            pub fn as_str(&self) -> &str {
68                &self.0
69            }
70
71            /// Consumes the value and returns the stored text.
72            #[must_use]
73            pub fn into_string(self) -> String {
74                self.0
75            }
76        }
77
78        impl AsRef<str> for $name {
79            fn as_ref(&self) -> &str {
80                self.as_str()
81            }
82        }
83
84        impl fmt::Display for $name {
85            fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86                formatter.write_str(self.as_str())
87            }
88        }
89
90        impl FromStr for $name {
91            type Err = ApiPrimitiveError;
92
93            fn from_str(value: &str) -> Result<Self, Self::Err> {
94                Self::new(value)
95            }
96        }
97
98        impl TryFrom<&str> for $name {
99            type Error = ApiPrimitiveError;
100
101            fn try_from(value: &str) -> Result<Self, Self::Error> {
102                Self::new(value)
103            }
104        }
105    };
106}
107
108text_newtype!(ErrorCode);
109text_newtype!(ErrorMessage);
110text_newtype!(ErrorDetail);
111text_newtype!(FieldName);
112
113/// API error category labels.
114#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
115pub enum ErrorCategory {
116    /// A stable label variant.
117    Validation,
118    /// A stable label variant.
119    Authentication,
120    /// A stable label variant.
121    Authorization,
122    /// A stable label variant.
123    Conflict,
124    /// A stable label variant.
125    RateLimit,
126    /// A stable label variant.
127    NotFound,
128    /// A stable label variant.
129    Server,
130    /// A stable label variant.
131    Unknown,
132}
133
134impl ErrorCategory {
135    /// Returns the stable label.
136    #[must_use]
137    pub const fn as_str(self) -> &'static str {
138        match self {
139            Self::Validation => "validation",
140            Self::Authentication => "authentication",
141            Self::Authorization => "authorization",
142            Self::Conflict => "conflict",
143            Self::RateLimit => "rate-limit",
144            Self::NotFound => "not-found",
145            Self::Server => "server",
146            Self::Unknown => "unknown",
147        }
148    }
149}
150
151impl Default for ErrorCategory {
152    fn default() -> Self {
153        Self::Validation
154    }
155}
156
157impl fmt::Display for ErrorCategory {
158    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
159        formatter.write_str(self.as_str())
160    }
161}
162
163impl FromStr for ErrorCategory {
164    type Err = ApiPrimitiveError;
165
166    fn from_str(value: &str) -> Result<Self, Self::Err> {
167        let trimmed = value.trim();
168        if trimmed.is_empty() {
169            return Err(ApiPrimitiveError::Empty);
170        }
171        let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
172        match normalized.as_str() {
173            "validation" => Ok(Self::Validation),
174            "authentication" => Ok(Self::Authentication),
175            "authorization" => Ok(Self::Authorization),
176            "conflict" => Ok(Self::Conflict),
177            "rate-limit" => Ok(Self::RateLimit),
178            "not-found" => Ok(Self::NotFound),
179            "server" => Ok(Self::Server),
180            "unknown" => Ok(Self::Unknown),
181            _ => Err(ApiPrimitiveError::Unknown),
182        }
183    }
184}
185
186/// Lightweight metadata tying this crate's primary text and label together.
187#[derive(Clone, Debug, Eq, PartialEq)]
188pub struct PrimitiveMetadata {
189    name: ErrorCode,
190    kind: ErrorCategory,
191}
192
193impl PrimitiveMetadata {
194    /// Creates primitive metadata.
195    #[must_use]
196    pub const fn new(name: ErrorCode, kind: ErrorCategory) -> Self {
197        Self { name, kind }
198    }
199
200    /// Returns the primary text value.
201    #[must_use]
202    pub const fn name(&self) -> &ErrorCode {
203        &self.name
204    }
205
206    /// Returns the primary label.
207    #[must_use]
208    pub const fn kind(&self) -> ErrorCategory {
209        self.kind
210    }
211}
212
213/// Protocol-neutral API error envelope.
214#[derive(Clone, Debug, Eq, PartialEq)]
215pub struct ApiError {
216    code: ErrorCode,
217    message: ErrorMessage,
218    category: ErrorCategory,
219    retryable: bool,
220}
221
222impl ApiError {
223    /// Creates an API error envelope.
224    #[must_use]
225    pub const fn new(code: ErrorCode, message: ErrorMessage) -> Self {
226        Self {
227            code,
228            message,
229            category: ErrorCategory::Unknown,
230            retryable: false,
231        }
232    }
233
234    /// Sets the error category.
235    #[must_use]
236    pub const fn with_category(mut self, category: ErrorCategory) -> Self {
237        self.category = category;
238        self
239    }
240
241    /// Marks the error as retryable or not retryable.
242    #[must_use]
243    pub const fn with_retryable(mut self, retryable: bool) -> Self {
244        self.retryable = retryable;
245        self
246    }
247
248    /// Returns the error code.
249    #[must_use]
250    pub const fn code(&self) -> &ErrorCode {
251        &self.code
252    }
253
254    /// Returns true when retrying may be useful.
255    #[must_use]
256    pub const fn is_retryable(&self) -> bool {
257        self.retryable
258    }
259}
260
261/// A field-specific validation error.
262#[derive(Clone, Debug, Eq, PartialEq)]
263pub struct FieldError {
264    field: FieldName,
265    message: ErrorMessage,
266}
267
268impl FieldError {
269    /// Creates a field error.
270    #[must_use]
271    pub const fn new(field: FieldName, message: ErrorMessage) -> Self {
272        Self { field, message }
273    }
274}
275
276#[cfg(test)]
277mod tests {
278    use super::*;
279
280    #[test]
281    fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
282        let value = ErrorCode::new("invalid-request")?;
283
284        assert_eq!(value.as_str(), "invalid-request");
285        assert_eq!(value.to_string(), "invalid-request");
286        assert_eq!("invalid-request".parse::<ErrorCode>()?, value);
287        Ok(())
288    }
289
290    #[test]
291    fn rejects_empty_text() {
292        assert_eq!(ErrorCode::new(""), Err(ApiPrimitiveError::Empty));
293    }
294
295    #[test]
296    fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
297        let kind = "validation".parse::<ErrorCategory>()?;
298
299        assert_eq!(kind, ErrorCategory::Validation);
300        assert_eq!(kind.to_string(), "validation");
301        Ok(())
302    }
303
304    #[test]
305    fn creates_metadata() -> Result<(), ApiPrimitiveError> {
306        let metadata =
307            PrimitiveMetadata::new(ErrorCode::new("invalid-request")?, ErrorCategory::default());
308
309        assert_eq!(metadata.name().as_str(), "invalid-request");
310        assert_eq!(metadata.kind(), ErrorCategory::default());
311        Ok(())
312    }
313}