|
| 1 | +# Exception Handling |
| 2 | + |
| 3 | +The library implements a comprehensive exception system to help you handle |
| 4 | +errors effectively. Understanding these exceptions will help you write more |
| 5 | +robust code. |
| 6 | + |
| 7 | +## Exception Hierarchy |
| 8 | + |
| 9 | +``` |
| 10 | +Exception |
| 11 | +├── ValueError |
| 12 | +│ └── ClientValidationException # Superclass for validations that take place before |
| 13 | +│ │ # making a request |
| 14 | +│ ├── InvalidDateException # Raised when a date string is not in the correct |
| 15 | +│ │ # format or not a valid calendar date |
| 16 | +│ ├── InvalidDateRangeException # Raised when a date range is invalid (e.g., end is |
| 17 | +│ │ # before start, exceeds max days) |
| 18 | +│ ├── PaginationException # Raised when pagination parameters are invalid |
| 19 | +│ ├── IntradayValidationException # Raised when intraday request parameters are invalid |
| 20 | +│ ├── ParameterValidationException # Raised when a parameter value is invalid |
| 21 | +│ │ # (e.g., negative when positive required) |
| 22 | +│ └── MissingParameterException # Raised when required parameters are missing or |
| 23 | +│ # parameter combinations are invalid |
| 24 | +│ |
| 25 | +└── FitbitAPIException # Base exception for all Fitbit API errors |
| 26 | + │ |
| 27 | + ├── OAuthException # Superclass for all authentication flow exceptions |
| 28 | + │ ├── ExpiredTokenException # Raised when the OAuth token has expired |
| 29 | + │ ├── InvalidGrantException # Raised when the grant_type value is invalid |
| 30 | + │ ├── InvalidTokenException # Raised when the OAuth token is invalid |
| 31 | + │ └── InvalidClientException # Raised when the client_id is invalid |
| 32 | + │ |
| 33 | + └── RequestException # Superclass for all API request exceptions |
| 34 | + ├── InvalidRequestException # Raised when the request syntax is invalid |
| 35 | + ├── AuthorizationException # Raised when there are authorization-related errors |
| 36 | + ├── InsufficientPermissionsException # Raised when the application has insufficient permissions |
| 37 | + ├── InsufficientScopeException # Raised when the application is missing a required scope |
| 38 | + ├── NotFoundException # Raised when the requested resource does not exist |
| 39 | + ├── RateLimitExceededException # Raised when the application hits rate limiting quotas |
| 40 | + ├── SystemException # Raised when there is a system-level failure |
| 41 | + └── ValidationException # Raised when a request parameter is invalid or missing |
| 42 | +``` |
| 43 | + |
| 44 | +## Client Validation Exceptions |
| 45 | + |
| 46 | +Client validation exceptions (`ClientValidationException` and its subclasses) |
| 47 | +are raised *before* any API call is made: |
| 48 | + |
| 49 | +1. They reflect problems with your input parameters that can be detected locally |
| 50 | +2. No network requests have been initiated when these exceptions occur |
| 51 | +3. They help you fix issues before consuming API rate limits |
| 52 | + |
| 53 | +```python |
| 54 | +from fitbit_client.exceptions import InvalidDateException, InvalidDateRangeException |
| 55 | + |
| 56 | +try: |
| 57 | + client.sleep.get_sleep_log_by_date_range( |
| 58 | + start_date="2024-01-01", |
| 59 | + end_date="2023-12-31" # End date before start date |
| 60 | + ) |
| 61 | +except InvalidDateRangeException as e: |
| 62 | + print(f"Date range error: {e.message}") |
| 63 | + print(f"Start date: {e.start_date}, End date: {e.end_date}") |
| 64 | + print(f"Resource: {e.resource_name}, Max days: {e.max_days}") |
| 65 | +``` |
| 66 | + |
| 67 | +### Common Client Validation Exceptions |
| 68 | + |
| 69 | +- **InvalidDateException**: Raised when a date string is not valid |
| 70 | +- **InvalidDateRangeException**: Raised when a date range is invalid |
| 71 | +- **ParameterValidationException**: Raised when a parameter value is invalid |
| 72 | +- **MissingParameterException**: Raised when required parameters are missing |
| 73 | +- **PaginationException**: Raised when pagination parameters are invalid |
| 74 | +- **IntradayValidationException**: Raised when intraday request parameters are |
| 75 | + invalid |
| 76 | + |
| 77 | +## API Exceptions |
| 78 | + |
| 79 | +API exceptions (`FitbitAPIException` and its subclasses) are raised in response |
| 80 | +to errors returned by the Fitbit API: |
| 81 | + |
| 82 | +```python |
| 83 | +from fitbit_client.exceptions import AuthorizationException, RateLimitExceededException |
| 84 | + |
| 85 | +try: |
| 86 | + client.activity.get_lifetime_stats() |
| 87 | +except AuthorizationException as e: |
| 88 | + print(f"Auth error ({e.status_code}): {e.message}") |
| 89 | + # Handle authentication error (e.g., refresh token, prompt for re-auth) |
| 90 | +except RateLimitExceededException as e: |
| 91 | + retry_after = int(e.headers.get("Retry-After", 60)) |
| 92 | + print(f"Rate limit exceeded. Retry after {retry_after} seconds") |
| 93 | + # Implement backoff strategy |
| 94 | +``` |
| 95 | + |
| 96 | +### Common API Exceptions |
| 97 | + |
| 98 | +- **AuthorizationException**: Authentication or authorization issues |
| 99 | +- **InvalidRequestException**: Invalid request syntax or parameters |
| 100 | +- **RateLimitExceededException**: API rate limits exceeded |
| 101 | +- **NotFoundException**: Requested resource doesn't exist |
| 102 | +- **SystemException**: Fitbit API server-side errors |
| 103 | + |
| 104 | +## Exception Properties |
| 105 | + |
| 106 | +### Client Validation Exceptions |
| 107 | + |
| 108 | +All client validation exceptions have these properties: |
| 109 | + |
| 110 | +- `message`: Human-readable error description |
| 111 | +- `field_name`: Name of the invalid field (if applicable) |
| 112 | + |
| 113 | +Specific validation exception types add additional properties: |
| 114 | + |
| 115 | +- **InvalidDateException**: `date_str` (the invalid date string) |
| 116 | +- **InvalidDateRangeException**: `start_date`, `end_date`, `max_days`, |
| 117 | + `resource_name` |
| 118 | +- **IntradayValidationException**: `allowed_values`, `resource_name` |
| 119 | + |
| 120 | +### API Exceptions |
| 121 | + |
| 122 | +All API exceptions have these properties: |
| 123 | + |
| 124 | +- `message`: Human-readable error description |
| 125 | +- `status_code`: HTTP status code (if applicable) |
| 126 | +- `error_type`: Type of error from the API |
| 127 | +- `field_name`: Name of the invalid field (for validation errors) |
| 128 | +- `headers`: Response headers (useful for rate limiting info) |
| 129 | + |
| 130 | +## Usage Patterns |
| 131 | + |
| 132 | +### Catching Specific Exceptions |
| 133 | + |
| 134 | +Target specific exceptions for tailored error handling: |
| 135 | + |
| 136 | +```python |
| 137 | +try: |
| 138 | + client.activity.create_activity_goals( |
| 139 | + period=ActivityGoalPeriod.DAILY, |
| 140 | + type=ActivityGoalType.STEPS, |
| 141 | + value=-1000 |
| 142 | + ) |
| 143 | +except ParameterValidationException as e: |
| 144 | + print(f"Invalid value for {e.field_name}: {e.message}") |
| 145 | +except AuthorizationException as e: |
| 146 | + print(f"Authorization error: {e.message}") |
| 147 | +except RateLimitExceededException as e: |
| 148 | + print(f"Rate limit error: {e.message}") |
| 149 | +``` |
| 150 | + |
| 151 | +### Catching Base Exception Classes |
| 152 | + |
| 153 | +Catch base classes to handle related exceptions together: |
| 154 | + |
| 155 | +```python |
| 156 | +try: |
| 157 | + client.activity.get_daily_activity_summary("today") |
| 158 | +except ClientValidationException as e: |
| 159 | + print(f"Invalid input: {e.message}") # Catches all input validation errors |
| 160 | +except OAuthException as e: |
| 161 | + print(f"OAuth error: {e.message}") # Catches all OAuth-related errors |
| 162 | +except FitbitAPIException as e: |
| 163 | + print(f"API error: {e.message}") # Catches all other API errors |
| 164 | +``` |
| 165 | + |
| 166 | +## Debugging APIs |
| 167 | + |
| 168 | +Every method accepts a `debug` parameter that prints the equivalent cURL |
| 169 | +command: |
| 170 | + |
| 171 | +```python |
| 172 | +client.activity.get_daily_activity_summary( |
| 173 | + date="today", |
| 174 | + debug=True |
| 175 | +) |
| 176 | +# Prints: |
| 177 | +# curl -X GET -H "Authorization: Bearer <token>" ... |
| 178 | +``` |
| 179 | + |
| 180 | +This helps troubleshoot API interactions by showing the exact request being |
| 181 | +made. |
0 commit comments