1use std::error;
7use std::fmt;
8use std::io;
9use std::str::Utf8Error;
10use std::sync::Arc;
11
12#[derive(Clone, Debug)]
14pub enum Error {
15 Api {
17 status_code: u16,
19 error_type: Option<String>,
21 message: String,
23 request_id: Option<String>,
25 retry_after: Option<u64>,
27 },
28
29 Authentication {
31 message: String,
33 },
34
35 Permission {
37 message: String,
39 },
40
41 NotFound {
43 message: String,
45 resource_type: Option<String>,
47 resource_id: Option<String>,
49 },
50
51 RateLimit {
53 status_code: u16,
55 message: String,
57 retry_after: Option<u64>,
59 },
60
61 BadRequest {
63 message: String,
65 param: Option<String>,
67 },
68
69 Timeout {
71 status_code: Option<u16>,
73 message: String,
75 duration: Option<f64>,
77 },
78
79 Abort {
81 message: String,
83 },
84
85 Connection {
87 message: String,
89 source: Option<Arc<dyn error::Error + Send + Sync>>,
91 },
92
93 InternalServer {
95 message: String,
97 request_id: Option<String>,
99 retry_after: Option<u64>,
101 },
102
103 ServiceUnavailable {
105 status_code: u16,
107 message: String,
109 retry_after: Option<u64>,
111 },
112
113 Serialization {
115 message: String,
117 source: Option<Arc<dyn error::Error + Send + Sync>>,
119 },
120
121 Io {
123 message: String,
125 source: Arc<io::Error>,
127 },
128
129 HttpClient {
131 message: String,
133 source: Option<Arc<dyn error::Error + Send + Sync>>,
135 },
136
137 Validation {
139 message: String,
141 param: Option<String>,
143 },
144
145 Url {
147 message: String,
149 source: Option<url::ParseError>,
151 },
152
153 Streaming {
155 message: String,
157 source: Option<Arc<dyn error::Error + Send + Sync>>,
159 },
160
161 Encoding {
163 message: String,
165 source: Option<Arc<dyn error::Error + Send + Sync>>,
167 },
168
169 Unknown {
171 message: String,
173 },
174
175 ToDo {
177 message: String,
179 },
180}
181
182impl Error {
183 pub fn api(
185 status_code: u16,
186 error_type: Option<String>,
187 message: String,
188 request_id: Option<String>,
189 ) -> Self {
190 Error::Api { status_code, error_type, message, request_id, retry_after: None }
191 }
192
193 pub fn authentication(message: impl Into<String>) -> Self {
195 Error::Authentication { message: message.into() }
196 }
197
198 pub fn permission(message: impl Into<String>) -> Self {
200 Error::Permission { message: message.into() }
201 }
202
203 pub fn not_found(
205 message: impl Into<String>,
206 resource_type: Option<String>,
207 resource_id: Option<String>,
208 ) -> Self {
209 Error::NotFound { message: message.into(), resource_type, resource_id }
210 }
211
212 pub fn rate_limit(message: impl Into<String>, retry_after: Option<u64>) -> Self {
214 Error::RateLimit { status_code: 429, message: message.into(), retry_after }
215 }
216
217 pub fn bad_request(message: impl Into<String>, param: Option<String>) -> Self {
219 Error::BadRequest { message: message.into(), param }
220 }
221
222 pub fn timeout(message: impl Into<String>, duration: Option<f64>) -> Self {
224 Error::Timeout { status_code: None, message: message.into(), duration }
225 }
226
227 pub fn abort(message: impl Into<String>) -> Self {
229 Error::Abort { message: message.into() }
230 }
231
232 pub fn connection(
234 message: impl Into<String>,
235 source: Option<Box<dyn error::Error + Send + Sync>>,
236 ) -> Self {
237 Error::Connection { message: message.into(), source: source.map(Arc::from) }
238 }
239
240 pub fn internal_server(message: impl Into<String>, request_id: Option<String>) -> Self {
242 Error::InternalServer { message: message.into(), request_id, retry_after: None }
243 }
244
245 pub fn service_unavailable(message: impl Into<String>, retry_after: Option<u64>) -> Self {
247 Error::ServiceUnavailable { status_code: 529, message: message.into(), retry_after }
248 }
249
250 pub fn serialization(
252 message: impl Into<String>,
253 source: Option<Box<dyn error::Error + Send + Sync>>,
254 ) -> Self {
255 Error::Serialization { message: message.into(), source: source.map(Arc::from) }
256 }
257
258 pub fn io(message: impl Into<String>, source: io::Error) -> Self {
260 Error::Io { message: message.into(), source: Arc::new(source) }
261 }
262
263 pub fn http_client(
265 message: impl Into<String>,
266 source: Option<Box<dyn error::Error + Send + Sync>>,
267 ) -> Self {
268 Error::HttpClient { message: message.into(), source: source.map(Arc::from) }
269 }
270
271 pub fn validation(message: impl Into<String>, param: Option<String>) -> Self {
273 Error::Validation { message: message.into(), param }
274 }
275
276 pub fn url(message: impl Into<String>, source: Option<url::ParseError>) -> Self {
278 Error::Url { message: message.into(), source }
279 }
280
281 pub fn streaming(
283 message: impl Into<String>,
284 source: Option<Box<dyn error::Error + Send + Sync>>,
285 ) -> Self {
286 Error::Streaming { message: message.into(), source: source.map(Arc::from) }
287 }
288
289 pub fn encoding(
291 message: impl Into<String>,
292 source: Option<Box<dyn error::Error + Send + Sync>>,
293 ) -> Self {
294 Error::Encoding { message: message.into(), source: source.map(Arc::from) }
295 }
296
297 pub fn unknown(message: impl Into<String>) -> Self {
299 Error::Unknown { message: message.into() }
300 }
301
302 pub fn todo(message: impl Into<String>) -> Self {
304 Error::ToDo { message: message.into() }
305 }
306
307 pub fn is_authentication(&self) -> bool {
309 matches!(self, Error::Authentication { .. })
310 }
311
312 pub fn is_permission(&self) -> bool {
314 matches!(self, Error::Permission { .. })
315 }
316
317 pub fn is_not_found(&self) -> bool {
319 matches!(self, Error::NotFound { .. })
320 }
321
322 pub fn is_rate_limit(&self) -> bool {
324 matches!(self, Error::RateLimit { .. })
325 }
326
327 pub fn is_bad_request(&self) -> bool {
329 matches!(self, Error::BadRequest { .. })
330 }
331
332 pub fn is_timeout(&self) -> bool {
334 matches!(self, Error::Timeout { .. })
335 }
336
337 pub fn is_abort(&self) -> bool {
339 matches!(self, Error::Abort { .. })
340 }
341
342 pub fn is_connection(&self) -> bool {
344 matches!(self, Error::Connection { .. })
345 }
346
347 pub fn is_server_error(&self) -> bool {
349 matches!(self, Error::InternalServer { .. } | Error::ServiceUnavailable { .. })
350 }
351
352 pub fn is_retryable(&self) -> bool {
354 match self {
355 Error::Api { status_code, .. } => {
356 matches!(status_code, 408 | 409 | 429 | 500..=599)
357 }
358 Error::Timeout { .. } => true,
359 Error::Connection { .. } => true,
360 Error::RateLimit { .. } => true,
361 Error::ServiceUnavailable { .. } => true,
362 Error::InternalServer { .. } => true,
363 _ => false,
364 }
365 }
366
367 pub fn is_todo(&self) -> bool {
369 matches!(self, Error::ToDo { .. })
370 }
371
372 pub fn is_validation(&self) -> bool {
374 matches!(self, Error::Validation { .. })
375 }
376
377 pub fn request_id(&self) -> Option<&str> {
379 match self {
380 Error::Api { request_id, .. } => request_id.as_deref(),
381 Error::InternalServer { request_id, .. } => request_id.as_deref(),
382 _ => None,
383 }
384 }
385
386 pub fn retry_after(&self) -> Option<u64> {
395 match self {
396 Self::Api { retry_after, .. }
397 | Self::RateLimit { retry_after, .. }
398 | Self::InternalServer { retry_after, .. }
399 | Self::ServiceUnavailable { retry_after, .. } => *retry_after,
400 _ => None,
401 }
402 }
403
404 pub fn status_code(&self) -> Option<u16> {
406 match self {
407 Error::Api { status_code, .. }
408 | Error::RateLimit { status_code, .. }
409 | Error::ServiceUnavailable { status_code, .. } => Some(*status_code),
410 Error::Timeout { status_code, .. } => *status_code,
411 Error::InternalServer { .. } => Some(500),
412 Error::Authentication { .. } => Some(401),
413 Error::Permission { .. } => Some(403),
414 Error::NotFound { .. } => Some(404),
415 Error::BadRequest { .. } => Some(400),
416 _ => None,
417 }
418 }
419}
420
421impl fmt::Display for Error {
422 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423 match self {
424 Error::Api { message, error_type, request_id, .. } => {
425 if let Some(error_type) = error_type {
426 if let Some(request_id) = request_id {
427 write!(f, "{error_type}: {message} (Request ID: {request_id})")
428 } else {
429 write!(f, "{error_type}: {message}")
430 }
431 } else if let Some(request_id) = request_id {
432 write!(f, "API error: {message} (Request ID: {request_id})")
433 } else {
434 write!(f, "API error: {message}")
435 }
436 }
437 Error::Authentication { message } => {
438 write!(f, "Authentication error: {message}")
439 }
440 Error::Permission { message } => {
441 write!(f, "Permission error: {message}")
442 }
443 Error::NotFound { message, resource_type, resource_id } => {
444 let prefix = if let Some(resource_type) = resource_type {
445 format!("Resource not found ({resource_type})")
446 } else {
447 "Resource not found".to_string()
448 };
449
450 let suffix = if let Some(resource_id) = resource_id {
451 format!(" [ID: {resource_id}]")
452 } else {
453 "".to_string()
454 };
455
456 write!(f, "{prefix}: {message}{suffix}")
457 }
458 Error::RateLimit { message, retry_after, .. } => {
459 if let Some(retry_after) = retry_after {
460 write!(f, "Rate limit exceeded: {message} (retry after {retry_after} seconds)")
461 } else {
462 write!(f, "Rate limit exceeded: {message}")
463 }
464 }
465 Error::BadRequest { message, param } => {
466 if let Some(param) = param {
467 write!(f, "Bad request: {message} (parameter: {param})")
468 } else {
469 write!(f, "Bad request: {message}")
470 }
471 }
472 Error::Timeout { message, duration, .. } => {
473 if let Some(duration) = duration {
474 write!(f, "Timeout error: {message} ({duration} seconds)")
475 } else {
476 write!(f, "Timeout error: {message}")
477 }
478 }
479 Error::Abort { message } => {
480 write!(f, "Request aborted: {message}")
481 }
482 Error::Connection { message, .. } => {
483 write!(f, "Connection error: {message}")
484 }
485 Error::InternalServer { message, request_id, .. } => {
486 if let Some(request_id) = request_id {
487 write!(f, "Internal server error: {message} (Request ID: {request_id})")
488 } else {
489 write!(f, "Internal server error: {message}")
490 }
491 }
492 Error::ServiceUnavailable { message, retry_after, .. } => {
493 if let Some(retry_after) = retry_after {
494 write!(f, "Service unavailable: {message} (retry after {retry_after} seconds)")
495 } else {
496 write!(f, "Service unavailable: {message}")
497 }
498 }
499 Error::Serialization { message, .. } => {
500 write!(f, "Serialization error: {message}")
501 }
502 Error::Io { message, .. } => {
503 write!(f, "I/O error: {message}")
504 }
505 Error::HttpClient { message, .. } => {
506 write!(f, "HTTP client error: {message}")
507 }
508 Error::Validation { message, param } => {
509 if let Some(param) = param {
510 write!(f, "Validation error: {message} (parameter: {param})")
511 } else {
512 write!(f, "Validation error: {message}")
513 }
514 }
515 Error::Url { message, .. } => {
516 write!(f, "URL error: {message}")
517 }
518 Error::Streaming { message, .. } => {
519 write!(f, "Streaming error: {message}")
520 }
521 Error::Encoding { message, .. } => {
522 write!(f, "Encoding error: {message}")
523 }
524 Error::Unknown { message } => {
525 write!(f, "Unknown error: {message}")
526 }
527 Error::ToDo { message } => {
528 write!(f, "Unimplemented: {message}")
529 }
530 }
531 }
532}
533
534impl error::Error for Error {
535 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
536 match self {
537 Error::Connection { source, .. } => {
538 source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
539 }
540 Error::Serialization { source, .. } => {
541 source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
542 }
543 Error::Io { source, .. } => Some(source),
544 Error::HttpClient { source, .. } => {
545 source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
546 }
547 Error::Url { source, .. } => {
548 source.as_ref().map(|e| e as &(dyn error::Error + 'static))
549 }
550 Error::Streaming { source, .. } => {
551 source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
552 }
553 Error::Encoding { source, .. } => {
554 source.as_ref().map(|e| e.as_ref() as &(dyn error::Error + 'static))
555 }
556 _ => None,
557 }
558 }
559}
560
561impl From<io::Error> for Error {
562 fn from(err: io::Error) -> Self {
563 Error::io(err.to_string(), err)
564 }
565}
566
567impl From<serde_json::Error> for Error {
568 fn from(err: serde_json::Error) -> Self {
569 Error::serialization(format!("JSON error: {err}"), Some(Box::new(err)))
570 }
571}
572
573impl From<url::ParseError> for Error {
574 fn from(err: url::ParseError) -> Self {
575 Error::url(format!("URL parse error: {err}"), Some(err))
576 }
577}
578
579impl From<Utf8Error> for Error {
580 fn from(err: Utf8Error) -> Self {
581 Error::encoding(format!("UTF-8 error: {err}"), Some(Box::new(err)))
582 }
583}
584
585impl From<crate::types::ApiError> for Error {
600 fn from(err: crate::types::ApiError) -> Self {
601 let crate::types::ApiError { error_type, message } = err;
602 match error_type.as_str() {
603 "overloaded_error" => Error::service_unavailable(message, None),
604 "rate_limit_error" => Error::rate_limit(message, None),
605 "api_error" => Error::internal_server(message, None),
606 "timeout_error" => Error::timeout(message, None),
607 "authentication_error" => Error::authentication(message),
608 "permission_error" => Error::permission(message),
609 "not_found_error" => Error::not_found(message, None, None),
610 "invalid_request_error" => Error::bad_request(message, None),
611 "billing_error" => Error::api(402, Some(error_type), message, None),
612 "request_too_large" => Error::api(413, Some(error_type), message, None),
613 _ => Error::streaming(format!("{error_type}: {message}"), None),
614 }
615 }
616}
617
618pub type Result<T> = std::result::Result<T, Error>;