Skip to main content

claude_usage/
error.rs

1//! Error types for the claude-usage crate.
2
3use thiserror::Error;
4
5/// Errors that can occur when retrieving credentials.
6#[derive(Debug, Error)]
7pub enum CredentialError {
8    /// Claude Code credentials not found in the platform's secure storage.
9    #[error("Claude Code credentials not found. Run `claude` to login.")]
10    NotFound,
11
12    /// Credentials have expired and need to be refreshed.
13    #[error("Credentials expired. Run `claude` to re-login.")]
14    Expired,
15
16    /// Failed to parse the credential JSON.
17    #[error("Failed to parse credentials: {0}")]
18    Parse(String),
19
20    /// Required field is missing from credentials.
21    #[error("Missing field in credentials: {0}")]
22    MissingField(&'static str),
23
24    /// Permission denied when accessing credentials.
25    #[error("Permission denied accessing credentials: {0}")]
26    Permission(String),
27
28    /// I/O error when reading credentials.
29    #[error("I/O error reading credentials: {0}")]
30    Io(String),
31
32    /// HOME directory not set (Linux/Unix).
33    #[error("HOME environment variable not set")]
34    NoHomeDir,
35}
36
37/// Errors that can occur when calling the Anthropic API.
38#[derive(Debug, Error)]
39pub enum ApiError {
40    /// Network error during HTTP request.
41    #[error("Network error: {0}")]
42    Network(String),
43
44    /// API returned 401 Unauthorized - token is invalid or expired.
45    #[error("Unauthorized. Run `claude` to re-login.")]
46    Unauthorized,
47
48    /// API returned 429 Too Many Requests.
49    #[error("Rate limited. Retry after: {retry_after:?}")]
50    RateLimited {
51        /// Value of the retry-after header, if present.
52        retry_after: Option<String>,
53    },
54
55    /// API returned 5xx server error.
56    #[error("Server error: {0}")]
57    Server(u16),
58
59    /// API returned an unexpected status code.
60    #[error("Unexpected status code: {0}")]
61    Unexpected(u16),
62}
63
64/// Unified error type for [`get_usage()`](crate::get_usage).
65///
66/// This error type wraps all possible errors that can occur when
67/// fetching usage data.
68#[derive(Debug, Error)]
69pub enum Error {
70    /// Error retrieving credentials.
71    #[error(transparent)]
72    Credential(#[from] CredentialError),
73
74    /// Error calling the API.
75    #[error(transparent)]
76    Api(#[from] ApiError),
77
78    /// Error parsing the API response.
79    #[error("Failed to parse API response: {0}")]
80    Parse(String),
81}