1use std::time::Duration;
8
9use thiserror::Error;
10
11#[derive(Debug, Error)]
16#[non_exhaustive]
17pub enum ErrorKind {
18 #[error("authentication failed: {0}")]
20 Authentication(String),
21
22 #[error("bad request: {0}")]
24 BadRequest(String),
25
26 #[error("not found: {0}")]
28 NotFound(String),
29
30 #[error("unprocessable entity: {0}")]
32 UnprocessableEntity(String),
33
34 #[error("rate limit exceeded: {0}")]
36 RateLimit(String),
37
38 #[error("internal server error: {0}")]
40 InternalServer(String),
41
42 #[error("service overloaded: {0}")]
44 Overloaded(String),
45
46 #[error("request timeout: {0}")]
50 RequestTimeout(String),
51
52 #[error("API error (status {status}): {message}")]
60 Api {
61 status: u16,
63 message: String,
65 },
66
67 #[error("connection error: {0}")]
69 Connection(String),
70
71 #[error("request timed out (configured timeout: {0:?})")]
73 Timeout(Duration),
74
75 #[error("response validation error: {message}{}", field_path.as_ref().map(|p| format!(" (field: {p})")).unwrap_or_default())]
77 ResponseValidation {
78 message: String,
80 field_path: Option<String>,
83 },
84
85 #[error("{0}")]
88 Validation(String),
89
90 #[error("JSON error: {0}")]
92 Json(#[from] serde_json::Error),
93
94 #[error("transport error: {0}")]
99 Transport(String),
100
101 #[error("runtime error: {0}")]
104 Runtime(String),
105}
106
107impl ErrorKind {
108 pub fn is_retryable(&self) -> bool {
116 matches!(
117 self,
118 ErrorKind::RateLimit(_)
119 | ErrorKind::RequestTimeout(_)
120 | ErrorKind::Overloaded(_)
121 | ErrorKind::InternalServer(_)
122 | ErrorKind::Connection(_)
123 | ErrorKind::Timeout(_)
124 )
125 }
126}
127
128#[derive(Debug)]
134#[non_exhaustive]
135pub struct TypeSafeError {
136 kind: ErrorKind,
137 request_id: Option<String>,
138}
139
140impl TypeSafeError {
141 pub fn new(kind: ErrorKind) -> Self {
143 Self {
144 kind,
145 request_id: None,
146 }
147 }
148
149 pub fn with_request_id(kind: ErrorKind, request_id: Option<String>) -> Self {
151 Self { kind, request_id }
152 }
153
154 pub fn kind(&self) -> &ErrorKind {
156 &self.kind
157 }
158
159 pub fn request_id(&self) -> Option<&str> {
162 self.request_id.as_deref()
163 }
164
165 pub fn is_retryable(&self) -> bool {
168 self.kind.is_retryable()
169 }
170}
171
172impl std::fmt::Display for TypeSafeError {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 write!(f, "{}", self.kind)?;
175 if let Some(ref id) = self.request_id {
176 write!(f, " (request id: {id})")?;
177 }
178 Ok(())
179 }
180}
181
182impl std::error::Error for TypeSafeError {}
183
184impl From<serde_json::Error> for TypeSafeError {
185 fn from(e: serde_json::Error) -> Self {
186 Self::new(ErrorKind::Json(e))
187 }
188}
189
190impl From<ErrorKind> for TypeSafeError {
191 fn from(kind: ErrorKind) -> Self {
192 Self::new(kind)
193 }
194}
195
196pub type Result<T> = std::result::Result<T, TypeSafeError>;
198
199#[cfg(test)]
200mod tests {
201 use super::*;
202
203 #[test]
204 fn response_validation_with_field_path() {
205 let err = TypeSafeError::new(ErrorKind::ResponseValidation {
206 message: "expected a number".to_string(),
207 field_path: Some("answers.billing.noul".to_string()),
208 });
209 let display = format!("{err}");
210 assert!(display.contains("expected a number"));
211 assert!(display.contains("answers.billing.noul"));
212 }
213
214 #[test]
215 fn response_validation_without_field_path() {
216 let err = TypeSafeError::new(ErrorKind::ResponseValidation {
217 message: "malformed JSON".to_string(),
218 field_path: None,
219 });
220 let display = format!("{err}");
221 assert!(display.contains("malformed JSON"));
222 assert!(!display.contains("field:"));
223 }
224
225 #[test]
226 fn response_validation_is_not_retryable() {
227 let kind = ErrorKind::ResponseValidation {
228 message: "bad".to_string(),
229 field_path: None,
230 };
231 assert!(!kind.is_retryable());
232 }
233
234 #[test]
235 fn request_id_displayed_when_present() {
236 let err = TypeSafeError::with_request_id(
237 ErrorKind::Authentication("bad key".to_string()),
238 Some("req-123".to_string()),
239 );
240 let display = format!("{err}");
241 assert!(display.contains("bad key"));
242 assert!(display.contains("req-123"));
243 }
244
245 #[test]
246 fn request_id_absent_when_not_provided() {
247 let err = TypeSafeError::new(ErrorKind::Authentication("bad key".to_string()));
248 let display = format!("{err}");
249 assert!(display.contains("bad key"));
250 assert!(!display.contains("request id"));
251 }
252
253 #[test]
254 fn from_error_kind_creates_error() {
255 let kind = ErrorKind::Validation("test".to_string());
256 let err: TypeSafeError = kind.into();
257 assert!(matches!(err.kind(), ErrorKind::Validation(_)));
258 }
259}