1use crate::github::types::GraphQLError;
2use std::{error::Error, fmt};
3
4#[derive(Debug, Clone, Default)]
6pub struct RateLimitDetails {
7 pub message: String,
8 pub status: Option<u16>,
10 pub resource: Option<String>,
11 pub remaining: Option<u64>,
12 pub reset: Option<u64>,
13 pub retry_after: Option<String>,
15 pub request_id: Option<String>,
16 pub graphql_errors: Vec<GraphQLError>,
17}
18
19impl fmt::Display for RateLimitDetails {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 self.message.fmt(f)
22 }
23}
24
25#[derive(Debug)]
27pub enum DecodeError {
28 Http(reqwest::Error),
29 Json(serde_json::Error),
30 InvalidResponse(String),
31}
32
33impl From<String> for DecodeError {
34 fn from(message: String) -> Self {
35 Self::InvalidResponse(message)
36 }
37}
38impl From<&str> for DecodeError {
39 fn from(message: &str) -> Self {
40 Self::InvalidResponse(message.into())
41 }
42}
43impl fmt::Display for DecodeError {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 match self {
46 Self::Http(error) => error.fmt(f),
47 Self::Json(error) => error.fmt(f),
48 Self::InvalidResponse(message) => message.fmt(f),
49 }
50 }
51}
52impl Error for DecodeError {
53 fn source(&self) -> Option<&(dyn Error + 'static)> {
54 match self {
55 Self::Http(error) => Some(error),
56 Self::Json(error) => Some(error),
57 Self::InvalidResponse(_) => None,
58 }
59 }
60}
61
62#[derive(Debug)]
63#[non_exhaustive]
64pub enum GitHubError {
65 Cancelled,
67 NetworkError(reqwest::Error),
68 AuthenticationError(String),
69 AccessDeniedError(String),
70 NotFoundError(String),
71 RateLimitError(Box<RateLimitDetails>),
72 AccessBlockedError(String),
73 DmcaBlockedError(String),
74 InvalidInput(String),
75 PaginationError(String),
76 ApiError {
77 status: u16,
78 message: String,
79 },
80 GraphQLError(Vec<GraphQLError>),
81 ParseError(DecodeError),
82 ConfigError(String),
83 FallbackError {
88 graphql: Box<GitHubError>,
89 rest: Box<GitHubError>,
90 },
91}
92
93impl fmt::Display for GitHubError {
94 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95 match self {
96 Self::Cancelled => f.write_str("Operation cancelled"),
97 Self::NetworkError(error) => write!(f, "Network error: {error}"),
98 Self::AuthenticationError(message) => write!(f, "Authentication error: {message}"),
99 Self::AccessDeniedError(message) => write!(f, "Access denied: {message}"),
100 Self::NotFoundError(message) => write!(f, "Not found: {message}"),
101 Self::RateLimitError(details) => write!(f, "Rate limit exceeded: {details}"),
102 Self::AccessBlockedError(message) => write!(f, "Access blocked: {message}"),
103 Self::DmcaBlockedError(message) => {
104 write!(f, "Unavailable for legal reasons: {message}")
105 }
106 Self::PaginationError(message) => write!(f, "Pagination error: {message}"),
107 Self::InvalidInput(message) => write!(f, "Invalid input: {message}"),
108 Self::ApiError { status, message } => write!(f, "GitHub API error {status}: {message}"),
109 Self::GraphQLError(errors) => write!(
110 f,
111 "GraphQL errors: {}",
112 errors
113 .iter()
114 .map(|error| error.message.as_str())
115 .collect::<Vec<_>>()
116 .join("; ")
117 ),
118 Self::ParseError(error) => write!(f, "Failed to parse response: {error}"),
119 Self::FallbackError { graphql, rest } => write!(
120 f,
121 "GraphQL failed ({graphql}); REST fallback failed ({rest})"
122 ),
123 Self::ConfigError(message) => write!(f, "Configuration error: {message}"),
124 }
125 }
126}
127
128impl Error for GitHubError {
129 fn source(&self) -> Option<&(dyn Error + 'static)> {
130 match self {
131 Self::FallbackError { graphql, .. } => Some(graphql.as_ref()),
132 Self::NetworkError(error) => Some(error),
133 Self::ParseError(error) => Some(error),
134 _ => None,
135 }
136 }
137}
138
139impl From<reqwest::Error> for GitHubError {
140 fn from(error: reqwest::Error) -> Self {
141 if error.is_decode() {
142 Self::ParseError(DecodeError::Http(error))
143 } else {
144 Self::NetworkError(error)
145 }
146 }
147}
148impl From<serde_json::Error> for GitHubError {
149 fn from(error: serde_json::Error) -> Self {
150 Self::ParseError(DecodeError::Json(error))
151 }
152}
153
154pub type Result<T> = std::result::Result<T, GitHubError>;
155
156impl GitHubError {
157 pub(crate) fn with_repository_context(self, owner: &str, name: &str) -> Self {
159 match self {
160 Self::NotFoundError(_) => Self::NotFoundError(format!("{owner}/{name}")),
161 error => error,
162 }
163 }
164}
165
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168#[non_exhaustive]
169pub enum ErrorKind {
170 Authentication,
171 Permission,
172 NotFound,
173 RateLimit,
174 Timeout,
175 Network,
176 InvalidInput,
177 Pagination,
178 Cancelled,
179 Upstream,
180}
181impl GitHubError {
182 pub fn kind(&self) -> ErrorKind {
185 match self {
186 Self::AuthenticationError(_) => ErrorKind::Authentication,
187 Self::AccessDeniedError(_)
188 | Self::AccessBlockedError(_)
189 | Self::DmcaBlockedError(_) => ErrorKind::Permission,
190 Self::NotFoundError(_) => ErrorKind::NotFound,
191 Self::RateLimitError(_) => ErrorKind::RateLimit,
192 Self::NetworkError(e) if e.is_timeout() => ErrorKind::Timeout,
193 Self::NetworkError(_) => ErrorKind::Network,
194 Self::InvalidInput(_) | Self::ConfigError(_) => ErrorKind::InvalidInput,
195 Self::PaginationError(_) => ErrorKind::Pagination,
196 Self::Cancelled => ErrorKind::Cancelled,
197 Self::FallbackError { rest, .. } => rest.kind(),
199 Self::GraphQLError(errors) => {
200 let has = |types: &[&str]| {
201 errors
202 .iter()
203 .any(|e| e.error_type.as_deref().is_some_and(|t| types.contains(&t)))
204 };
205 if has(&["RATE_LIMITED"]) {
206 ErrorKind::RateLimit
207 } else if has(&["UNAUTHORIZED", "UNAUTHENTICATED"]) {
208 ErrorKind::Authentication
209 } else if has(&["FORBIDDEN", "INSUFFICIENT_SCOPES"]) {
210 ErrorKind::Permission
211 } else if !errors.is_empty()
212 && errors
213 .iter()
214 .all(|e| e.error_type.as_deref() == Some("NOT_FOUND"))
215 {
216 ErrorKind::NotFound
217 } else {
218 ErrorKind::Upstream
219 }
220 }
221 _ => ErrorKind::Upstream,
222 }
223 }
224}