Skip to main content

aptu_core/
error.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Error types for the aptu-core library.
4//!
5//! Uses `thiserror` for deriving `std::error::Error` implementations.
6//! Application code should use `anyhow::Result` for top-level error handling.
7
8use thiserror::Error;
9
10/// Errors that can occur during Aptu operations.
11#[derive(Error, Debug)]
12pub enum AptuError {
13    /// GitHub API error from octocrab.
14    #[error("GitHub API error: {message}")]
15    GitHub {
16        /// Error message.
17        message: String,
18    },
19
20    /// AI provider error (`OpenRouter`, Ollama, etc.).
21    #[error("AI provider error: {message}")]
22    AI {
23        /// Error message from the AI provider.
24        message: String,
25        /// Optional HTTP status code from the provider.
26        status: Option<u16>,
27        /// Name of the AI provider (e.g., `OpenRouter`, `Ollama`).
28        provider: String,
29    },
30
31    /// User is not authenticated - needs to run `aptu auth login`.
32    #[error(
33        "Authentication required - run `aptu auth login` first, or set GITHUB_TOKEN environment variable"
34    )]
35    NotAuthenticated,
36
37    /// AI provider is not authenticated - missing API key.
38    #[error("AI provider '{provider}' is not authenticated - set {env_var} environment variable")]
39    AiProviderNotAuthenticated {
40        /// Name of the AI provider (e.g., `OpenRouter`, `Ollama`).
41        provider: String,
42        /// Environment variable name to set (e.g., `OPENROUTER_API_KEY`).
43        env_var: String,
44    },
45
46    /// Rate limit exceeded from an AI provider.
47    #[error("Rate limit exceeded on {provider}, retry after {retry_after}s")]
48    RateLimited {
49        /// Name of the provider that rate limited (e.g., `OpenRouter`).
50        provider: String,
51        /// Number of seconds to wait before retrying.
52        retry_after: u64,
53    },
54
55    /// AI response was truncated (incomplete JSON due to EOF).
56    #[error("Truncated response from {provider} - response ended prematurely")]
57    TruncatedResponse {
58        /// Name of the AI provider that returned truncated response.
59        provider: String,
60    },
61
62    /// Configuration file error.
63    #[error("Configuration error: {message}")]
64    Config {
65        /// Error message.
66        message: String,
67    },
68
69    /// Invalid JSON response from AI provider.
70    #[error("Invalid JSON response from AI")]
71    InvalidAIResponse(#[source] serde_json::Error),
72
73    /// Network/HTTP error from reqwest.
74    #[error("Network error: {0}")]
75    Network(#[from] reqwest::Error),
76
77    /// Keyring/credential storage error.
78    #[cfg(feature = "keyring")]
79    #[error("Keyring error: {0}")]
80    Keyring(#[from] keyring_core::error::Error),
81
82    /// Circuit breaker is open - AI provider is unavailable.
83    #[error("Circuit breaker is open - AI provider is temporarily unavailable")]
84    CircuitOpen,
85
86    /// Type mismatch: reference is a different type than expected.
87    #[error("#{number} is {actual}, not {expected}")]
88    TypeMismatch {
89        /// The issue/PR number.
90        number: u64,
91        /// Expected type.
92        expected: ResourceType,
93        /// Actual type.
94        actual: ResourceType,
95    },
96
97    /// Model registry error (runtime model validation).
98    #[error("Model registry error: {message}")]
99    ModelRegistry {
100        /// Error message.
101        message: String,
102    },
103
104    /// Model validation error - invalid model ID with suggestions.
105    #[error("Invalid model ID: {model_id}. Did you mean one of these?\n{suggestions}")]
106    ModelValidation {
107        /// The invalid model ID provided by the user.
108        model_id: String,
109        /// Suggested valid model IDs based on fuzzy matching.
110        suggestions: String,
111    },
112
113    /// Security scan error.
114    #[error("Security scan error: {message}")]
115    SecurityScan {
116        /// Error message.
117        message: String,
118    },
119
120    /// A user-supplied input field exceeds its configured byte limit.
121    #[error(
122        "input field `{field}` exceeds limit: {actual_bytes} bytes (limit: {limit_bytes} bytes)"
123    )]
124    InputExceedsLimit {
125        /// Name of the field that exceeded the limit.
126        field: String,
127        /// Actual byte count of the input.
128        actual_bytes: usize,
129        /// Configured byte limit.
130        limit_bytes: usize,
131    },
132}
133
134/// GitHub resource type for type mismatch errors.
135#[derive(Debug, Clone, Copy)]
136pub enum ResourceType {
137    /// GitHub issue.
138    Issue,
139    /// GitHub pull request.
140    PullRequest,
141}
142
143impl std::fmt::Display for ResourceType {
144    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
145        match self {
146            ResourceType::Issue => write!(f, "issue"),
147            ResourceType::PullRequest => write!(f, "pull request"),
148        }
149    }
150}
151
152impl From<octocrab::Error> for AptuError {
153    fn from(err: octocrab::Error) -> Self {
154        AptuError::GitHub {
155            message: err.to_string(),
156        }
157    }
158}
159
160impl From<config::ConfigError> for AptuError {
161    fn from(err: config::ConfigError) -> Self {
162        AptuError::Config {
163            message: err.to_string(),
164        }
165    }
166}