Skip to main content

aptu_core/
error.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Error types for the Aptu CLI.
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::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
121/// GitHub resource type for type mismatch errors.
122#[derive(Debug, Clone, Copy)]
123pub enum ResourceType {
124    /// GitHub issue.
125    Issue,
126    /// GitHub pull request.
127    PullRequest,
128}
129
130impl std::fmt::Display for ResourceType {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        match self {
133            ResourceType::Issue => write!(f, "issue"),
134            ResourceType::PullRequest => write!(f, "pull request"),
135        }
136    }
137}
138
139impl From<octocrab::Error> for AptuError {
140    fn from(err: octocrab::Error) -> Self {
141        AptuError::GitHub {
142            message: err.to_string(),
143        }
144    }
145}
146
147impl From<config::ConfigError> for AptuError {
148    fn from(err: config::ConfigError) -> Self {
149        AptuError::Config {
150            message: err.to_string(),
151        }
152    }
153}