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