Skip to main content

endpoint_libs/libs/
error_code.rs

1use alloc::string::String;
2use core::str::FromStr;
3use serde::*;
4
5/// `ErrorCode` is a wrapper around `u32` that represents an error code.
6#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
7pub struct ErrorCode {
8    /// The error code (e.g. `100400` for BadRequest).
9    code: u32,
10}
11
12impl ErrorCode {
13    /// Indicated a bad request.
14    pub const BAD_REQUEST: Self = Self::new(100400);
15
16    /// Indicates that authentication is required.
17    pub const UNAUTHORIZED: Self = Self::new(100401);
18
19    /// Indicates that payment is required.
20    pub const PAYMENT_REQUIRED: Self = Self::new(100402);
21
22    /// Indicates forbidden access.
23    pub const FORBIDDEN: Self = Self::new(100403);
24
25    /// Indicates that the requested resource was not found.
26    pub const NOT_FOUND: Self = Self::new(100404);
27
28    /// Indicates that the request method is not allowed.
29    pub const METHOD_NOT_ALLOWED: Self = Self::new(100405);
30
31    /// Indicates that the requested response format is not acceptable.
32    pub const NOT_ACCEPTABLE: Self = Self::new(100406);
33
34    /// Indicates that proxy authentication is required.
35    pub const PROXY_AUTHENTICATION_REQUIRED: Self = Self::new(100407);
36
37    /// Indicates that the request timed out.
38    pub const REQUEST_TIMEOUT: Self = Self::new(100408);
39
40    /// Indicates that the request conflicts with current state.
41    pub const CONFLICT: Self = Self::new(100409);
42
43    /// Indicates that the requested resource is gone.
44    pub const GONE: Self = Self::new(100410);
45
46    /// Indicates that the request must include a content length.
47    pub const LENGTH_REQUIRED: Self = Self::new(100411);
48
49    /// Indicates that a precondition failed.
50    pub const PRECONDITION_FAILED: Self = Self::new(100412);
51
52    /// Indicates that the payload is too large.
53    pub const PAYLOAD_TOO_LARGE: Self = Self::new(100413);
54
55    /// Indicates that the URI is too long.
56    pub const URI_TOO_LONG: Self = Self::new(100414);
57
58    /// Indicates that the media type is unsupported.
59    pub const UNSUPPORTED_MEDIA_TYPE: Self = Self::new(100415);
60
61    /// Indicates that the requested range cannot be satisfied.
62    pub const RANGE_NOT_SATISFIABLE: Self = Self::new(100416);
63
64    /// Indicates that an expectation failed.
65    pub const EXPECTATION_FAILED: Self = Self::new(100417);
66
67    /// Indicates an I'm a teapot response.
68    pub const IM_A_TEAPOT: Self = Self::new(100418);
69
70    /// Indicates that the request was misdirected.
71    pub const MISDIRECTED_REQUEST: Self = Self::new(100421);
72
73    /// Indicates that the entity could not be processed.
74    pub const UNPROCESSABLE_ENTITY: Self = Self::new(100422);
75
76    /// Indicates that the resource is locked.
77    pub const LOCKED: Self = Self::new(100423);
78
79    /// Indicates a failed dependency.
80    pub const FAILED_DEPENDENCY: Self = Self::new(100424);
81
82    /// Indicates that the request must be upgraded.
83    pub const UPGRADE_REQUIRED: Self = Self::new(100426);
84
85    /// Indicates that a precondition is required.
86    pub const PRECONDITION_REQUIRED: Self = Self::new(100428);
87
88    /// Indicates too many requests.
89    pub const TOO_MANY_REQUESTS: Self = Self::new(100429);
90
91    /// Indicates that request header fields are too large.
92    pub const REQUEST_HEADER_FIELDS_TOO_LARGE: Self = Self::new(100431);
93
94    /// Indicates that the request is unavailable for legal reasons.
95    pub const UNAVAILABLE_FOR_LEGAL_REASONS: Self = Self::new(100451);
96
97    /// Indicates an internal server error.
98    pub const INTERNAL_ERROR: Self = Self::new(100500);
99
100    /// Indicates a non-implemented endpoint.
101    pub const NOT_IMPLEMENTED: Self = Self::new(100501);
102
103    /// Indicates a bad gateway.
104    pub const BAD_GATEWAY: Self = Self::new(100502);
105
106    /// Indicates that the service is unavailable.
107    pub const SERVICE_UNAVAILABLE: Self = Self::new(100503);
108
109    /// Indicates a gateway timeout.
110    pub const GATEWAY_TIMEOUT: Self = Self::new(100504);
111
112    /// Indicates that the HTTP version is not supported.
113    pub const HTTP_VERSION_NOT_SUPPORTED: Self = Self::new(100505);
114
115    /// Indicates that content negotiation also found a variant problem.
116    pub const VARIANT_ALSO_NEGOTIATES: Self = Self::new(100506);
117
118    /// Indicates insufficient storage.
119    pub const INSUFFICIENT_STORAGE: Self = Self::new(100507);
120
121    /// Indicates that a loop was detected.
122    pub const LOOP_DETECTED: Self = Self::new(100508);
123
124    /// Indicates that the request must be extended.
125    pub const NOT_EXTENDED: Self = Self::new(100510);
126
127    /// Indicates that network authentication is required.
128    pub const NETWORK_AUTHENTICATION_REQUIRED: Self = Self::new(100511);
129
130    /// Create a new `ErrorCode` from a `u32`.
131    pub const fn new(code: u32) -> Self {
132        Self { code }
133    }
134
135    /// Get the `ErrorCode` as a `u32`.
136    /// Just returns the code field.
137    pub const fn to_u32(self) -> u32 {
138        self.code
139    }
140
141    /// Getter for the `ErrorCode` code field.
142    pub const fn code(self) -> u32 {
143        self.to_u32()
144    }
145
146    pub const fn kind(self) -> &'static str {
147        match self.code {
148            100400 => "BadRequest",
149            100401 => "Unauthorized",
150            100402 => "PaymentRequired",
151            100403 => "Forbidden",
152            100404 => "NotFound",
153            100405 => "MethodNotAllowed",
154            100406 => "NotAcceptable",
155            100407 => "ProxyAuthenticationRequired",
156            100408 => "RequestTimeout",
157            100409 => "Conflict",
158            100410 => "Gone",
159            100411 => "LengthRequired",
160            100412 => "PreconditionFailed",
161            100413 => "PayloadTooLarge",
162            100414 => "UriTooLong",
163            100415 => "UnsupportedMediaType",
164            100416 => "RangeNotSatisfiable",
165            100417 => "ExpectationFailed",
166            100418 => "ImATeapot",
167            100421 => "MisdirectedRequest",
168            100422 => "UnprocessableEntity",
169            100423 => "Locked",
170            100424 => "FailedDependency",
171            100426 => "UpgradeRequired",
172            100428 => "PreconditionRequired",
173            100429 => "TooManyRequests",
174            100431 => "RequestHeaderFieldsTooLarge",
175            100451 => "UnavailableForLegalReasons",
176            100500 => "InternalError",
177            100501 => "NotImplemented",
178            100502 => "BadGateway",
179            100503 => "ServiceUnavailable",
180            100504 => "GatewayTimeout",
181            100505 => "HttpVersionNotSupported",
182            100506 => "VariantAlsoNegotiates",
183            100507 => "InsufficientStorage",
184            100508 => "LoopDetected",
185            100510 => "NotExtended",
186            100511 => "NetworkAuthenticationRequired",
187            _ => "CustomError",
188        }
189    }
190
191    pub fn from_name(name: &str) -> Option<Self> {
192        let normalized: String = name
193            .chars()
194            .filter(|c| c.is_ascii_alphanumeric())
195            .flat_map(char::to_uppercase)
196            .collect();
197
198        match normalized.as_str() {
199            "BADREQUEST" => Some(Self::BAD_REQUEST),
200            "UNAUTHORIZED" => Some(Self::UNAUTHORIZED),
201            "PAYMENTREQUIRED" => Some(Self::PAYMENT_REQUIRED),
202            "FORBIDDEN" => Some(Self::FORBIDDEN),
203            "NOTFOUND" => Some(Self::NOT_FOUND),
204            "METHODNOTALLOWED" => Some(Self::METHOD_NOT_ALLOWED),
205            "NOTACCEPTABLE" => Some(Self::NOT_ACCEPTABLE),
206            "PROXYAUTHENTICATIONREQUIRED" => Some(Self::PROXY_AUTHENTICATION_REQUIRED),
207            "REQUESTTIMEOUT" => Some(Self::REQUEST_TIMEOUT),
208            "CONFLICT" => Some(Self::CONFLICT),
209            "GONE" => Some(Self::GONE),
210            "LENGTHREQUIRED" => Some(Self::LENGTH_REQUIRED),
211            "PRECONDITIONFAILED" => Some(Self::PRECONDITION_FAILED),
212            "PAYLOADTOOLARGE" => Some(Self::PAYLOAD_TOO_LARGE),
213            "URITOOLONG" => Some(Self::URI_TOO_LONG),
214            "UNSUPPORTEDMEDIATYPE" => Some(Self::UNSUPPORTED_MEDIA_TYPE),
215            "RANGENOTSATISFIABLE" => Some(Self::RANGE_NOT_SATISFIABLE),
216            "EXPECTATIONFAILED" => Some(Self::EXPECTATION_FAILED),
217            "IMATEAPOT" => Some(Self::IM_A_TEAPOT),
218            "MISDIRECTEDREQUEST" => Some(Self::MISDIRECTED_REQUEST),
219            "UNPROCESSABLEENTITY" => Some(Self::UNPROCESSABLE_ENTITY),
220            "LOCKED" => Some(Self::LOCKED),
221            "FAILEDDEPENDENCY" => Some(Self::FAILED_DEPENDENCY),
222            "UPGRADEREQUIRED" => Some(Self::UPGRADE_REQUIRED),
223            "PRECONDITIONREQUIRED" => Some(Self::PRECONDITION_REQUIRED),
224            "TOOMANYREQUESTS" => Some(Self::TOO_MANY_REQUESTS),
225            "REQUESTHEADERFIELDSTOOLARGE" => Some(Self::REQUEST_HEADER_FIELDS_TOO_LARGE),
226            "UNAVAILABLEFORLEGALREASONS" => Some(Self::UNAVAILABLE_FOR_LEGAL_REASONS),
227            "INTERNALERROR" => Some(Self::INTERNAL_ERROR),
228            "NOTIMPLEMENTED" => Some(Self::NOT_IMPLEMENTED),
229            "BADGATEWAY" => Some(Self::BAD_GATEWAY),
230            "SERVICEUNAVAILABLE" => Some(Self::SERVICE_UNAVAILABLE),
231            "GATEWAYTIMEOUT" => Some(Self::GATEWAY_TIMEOUT),
232            "HTTPVERSIONNOTSUPPORTED" => Some(Self::HTTP_VERSION_NOT_SUPPORTED),
233            "VARIANTALSONEGOTIATES" => Some(Self::VARIANT_ALSO_NEGOTIATES),
234            "INSUFFICIENTSTORAGE" => Some(Self::INSUFFICIENT_STORAGE),
235            "LOOPDETECTED" => Some(Self::LOOP_DETECTED),
236            "NOTEXTENDED" => Some(Self::NOT_EXTENDED),
237            "NETWORKAUTHENTICATIONREQUIRED" => Some(Self::NETWORK_AUTHENTICATION_REQUIRED),
238            _ => None,
239        }
240    }
241}
242
243impl FromStr for ErrorCode {
244    type Err = ParseErrorCodeError;
245
246    fn from_str(value: &str) -> Result<Self, Self::Err> {
247        if let Some(code) = Self::from_name(value) {
248            return Ok(code);
249        }
250
251        value
252            .parse::<u32>()
253            .map(Self::new)
254            .map_err(|_| ParseErrorCodeError)
255    }
256}
257
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259pub struct ParseErrorCodeError;
260
261impl core::fmt::Display for ParseErrorCodeError {
262    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
263        f.write_str("invalid error code")
264    }
265}
266
267impl core::error::Error for ParseErrorCodeError {}