fitbit_rs/error.rs
1//! Error types for the Fitbit client.
2//!
3//! This module defines the various error types that can occur when interacting with
4//! the Fitbit API.
5
6use thiserror::Error;
7
8/// Errors that can occur when interacting with the Fitbit API
9#[derive(Error, Debug)]
10pub enum FitbitError {
11 /// Error occurring during HTTP request
12 #[error("Request failed: {0}")]
13 RequestError(#[from] ureq::Error),
14
15 /// Error parsing JSON response
16 #[error("JSON parsing failed: {0}")]
17 JsonError(String),
18
19 /// API rate limit exceeded
20 #[error("Rate limit exceeded - retry after {0} seconds")]
21 RateLimitExceeded(u64),
22
23 /// Authentication error
24 #[error("Authentication failed: {0}")]
25 AuthenticationError(String),
26
27 /// API responded with an error
28 #[error("API error: {status_code} - {message}")]
29 ApiError {
30 /// HTTP status code
31 status_code: u16,
32 /// Error message from the API
33 message: String,
34 },
35
36 /// Client configuration error
37 #[error("Client configuration error: {0}")]
38 ConfigurationError(String),
39
40 /// Error retrieving or using access token
41 #[error("Access token error: {0}")]
42 AccessTokenError(#[from] crate::access_token::AccessTokenError),
43}
44
45/// Helper functions for working with Fitbit errors
46impl FitbitError {
47 /// Creates a new API error from a status code and message
48 ///
49 /// # Arguments
50 ///
51 /// * `status_code` - HTTP status code
52 /// * `message` - Error message
53 ///
54 /// # Returns
55 ///
56 /// A new `FitbitError::ApiError`
57 pub fn api_error(status_code: u16, message: impl Into<String>) -> Self {
58 FitbitError::ApiError {
59 status_code,
60 message: message.into(),
61 }
62 }
63
64 /// Creates a new authentication error
65 ///
66 /// # Arguments
67 ///
68 /// * `message` - Error message
69 ///
70 /// # Returns
71 ///
72 /// A new `FitbitError::AuthenticationError`
73 pub fn authentication_error(message: impl Into<String>) -> Self {
74 FitbitError::AuthenticationError(message.into())
75 }
76
77 /// Checks if the error is a rate limit error
78 ///
79 /// # Returns
80 ///
81 /// `true` if the error is a rate limit error, `false` otherwise
82 pub fn is_rate_limit(&self) -> bool {
83 matches!(self, FitbitError::RateLimitExceeded(_))
84 }
85
86 /// Checks if the error is an authentication error
87 ///
88 /// # Returns
89 ///
90 /// `true` if the error is an authentication error, `false` otherwise
91 pub fn is_authentication_error(&self) -> bool {
92 matches!(self, FitbitError::AuthenticationError(_))
93 }
94
95 /// Checks if the error is a client configuration error
96 ///
97 /// # Returns
98 ///
99 /// `true` if the error is a client configuration error, `false` otherwise
100 pub fn is_configuration_error(&self) -> bool {
101 matches!(self, FitbitError::ConfigurationError(_))
102 }
103}