grow_apache_skywalking/core/
error.rs1use std::fmt;
5use std::str::FromStr;
6use std::sync::Arc;
7use std::time::Duration;
8
9pub type Result<T> = std::result::Result<T, Error>;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
14#[non_exhaustive]
15pub enum ErrorCode {
16 Config,
18 Authentication,
20 PermissionDenied,
22 NotFound,
24 Conflict,
26 RateLimited,
28 Validation,
30 Unavailable,
32 Timeout,
34 Unsupported,
36 Cancelled,
38}
39
40impl ErrorCode {
41 pub const ALL: [ErrorCode; 11] = [
43 ErrorCode::Config,
44 ErrorCode::Authentication,
45 ErrorCode::PermissionDenied,
46 ErrorCode::NotFound,
47 ErrorCode::Conflict,
48 ErrorCode::RateLimited,
49 ErrorCode::Validation,
50 ErrorCode::Unavailable,
51 ErrorCode::Timeout,
52 ErrorCode::Unsupported,
53 ErrorCode::Cancelled,
54 ];
55
56 pub fn as_str(self) -> &'static str {
58 match self {
59 ErrorCode::Config => "CONFIG",
60 ErrorCode::Authentication => "AUTHENTICATION",
61 ErrorCode::PermissionDenied => "PERMISSION_DENIED",
62 ErrorCode::NotFound => "NOT_FOUND",
63 ErrorCode::Conflict => "CONFLICT",
64 ErrorCode::RateLimited => "RATE_LIMITED",
65 ErrorCode::Validation => "VALIDATION",
66 ErrorCode::Unavailable => "UNAVAILABLE",
67 ErrorCode::Timeout => "TIMEOUT",
68 ErrorCode::Unsupported => "UNSUPPORTED",
69 ErrorCode::Cancelled => "CANCELLED",
70 }
71 }
72
73 pub fn default_retryable(self) -> bool {
75 matches!(
76 self,
77 ErrorCode::RateLimited | ErrorCode::Unavailable | ErrorCode::Timeout
78 )
79 }
80
81 pub fn reason(self) -> &'static str {
83 match self {
84 ErrorCode::Config => "invalid configuration",
85 ErrorCode::Authentication => "authentication failed",
86 ErrorCode::PermissionDenied => "permission denied",
87 ErrorCode::NotFound => "not found",
88 ErrorCode::Conflict => "conflict",
89 ErrorCode::RateLimited => "rate limited",
90 ErrorCode::Validation => "invalid request",
91 ErrorCode::Unavailable => "service unavailable",
92 ErrorCode::Timeout => "timed out",
93 ErrorCode::Unsupported => "not supported",
94 ErrorCode::Cancelled => "cancelled",
95 }
96 }
97
98 pub fn from_http_status(status: u16) -> Option<ErrorCode> {
100 Some(match status {
101 401 => ErrorCode::Authentication,
102 403 => ErrorCode::PermissionDenied,
103 404 => ErrorCode::NotFound,
104 409 | 412 => ErrorCode::Conflict,
105 429 => ErrorCode::RateLimited,
106 408 | 504 => ErrorCode::Timeout,
107 501 => ErrorCode::Unsupported,
108 400..=499 => ErrorCode::Validation,
109 500..=599 => ErrorCode::Unavailable,
110 _ => return None,
111 })
112 }
113}
114
115impl fmt::Display for ErrorCode {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.write_str(self.as_str())
118 }
119}
120
121impl FromStr for ErrorCode {
122 type Err = Error;
123
124 fn from_str(s: &str) -> Result<Self> {
125 ErrorCode::ALL
126 .into_iter()
127 .find(|c| c.as_str() == s)
128 .ok_or_else(|| Error::validation(format!("unknown error code {s:?}")))
129 }
130}
131
132#[derive(Clone)]
134pub struct ErrorContext {
135 message: String,
136 http_status: Option<u16>,
137 request_id: Option<String>,
138 retryable: bool,
139 retry_after: Option<Duration>,
140 source: Option<Arc<dyn std::error::Error + Send + Sync + 'static>>,
141}
142
143impl fmt::Debug for ErrorContext {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 f.debug_struct("ErrorContext")
146 .field("message", &self.message)
147 .field("http_status", &self.http_status)
148 .field("request_id", &self.request_id)
149 .field("retryable", &self.retryable)
150 .field("retry_after", &self.retry_after)
151 .field("source", &self.source.as_ref().map(|s| s.to_string()))
152 .finish()
153 }
154}
155
156#[derive(Debug, Clone)]
160#[non_exhaustive]
161pub enum Error {
162 Config(Box<ErrorContext>),
164 Authentication(Box<ErrorContext>),
166 PermissionDenied(Box<ErrorContext>),
168 NotFound(Box<ErrorContext>),
170 Conflict(Box<ErrorContext>),
172 RateLimited(Box<ErrorContext>),
174 Validation(Box<ErrorContext>),
176 Unavailable(Box<ErrorContext>),
178 Timeout(Box<ErrorContext>),
180 Unsupported(Box<ErrorContext>),
182 Cancelled(Box<ErrorContext>),
184}
185
186impl Error {
187 pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
189 let ctx = Box::new(ErrorContext {
190 message: message.into(),
191 http_status: None,
192 request_id: None,
193 retryable: code.default_retryable(),
194 retry_after: None,
195 source: None,
196 });
197 match code {
198 ErrorCode::Config => Error::Config(ctx),
199 ErrorCode::Authentication => Error::Authentication(ctx),
200 ErrorCode::PermissionDenied => Error::PermissionDenied(ctx),
201 ErrorCode::NotFound => Error::NotFound(ctx),
202 ErrorCode::Conflict => Error::Conflict(ctx),
203 ErrorCode::RateLimited => Error::RateLimited(ctx),
204 ErrorCode::Validation => Error::Validation(ctx),
205 ErrorCode::Unavailable => Error::Unavailable(ctx),
206 ErrorCode::Timeout => Error::Timeout(ctx),
207 ErrorCode::Unsupported => Error::Unsupported(ctx),
208 ErrorCode::Cancelled => Error::Cancelled(ctx),
209 }
210 }
211
212 pub fn from_status(status: u16, message: impl Into<String>) -> Self {
214 let code = ErrorCode::from_http_status(status).unwrap_or(ErrorCode::Unavailable);
215 Error::new(code, message).with_status(status)
216 }
217
218 pub fn config(message: impl Into<String>) -> Self {
220 Error::new(ErrorCode::Config, message)
221 }
222 pub fn validation(message: impl Into<String>) -> Self {
224 Error::new(ErrorCode::Validation, message)
225 }
226 pub fn not_found(message: impl Into<String>) -> Self {
228 Error::new(ErrorCode::NotFound, message)
229 }
230 pub fn conflict(message: impl Into<String>) -> Self {
232 Error::new(ErrorCode::Conflict, message)
233 }
234 pub fn timeout(message: impl Into<String>) -> Self {
236 Error::new(ErrorCode::Timeout, message)
237 }
238 pub fn unavailable(message: impl Into<String>) -> Self {
240 Error::new(ErrorCode::Unavailable, message)
241 }
242 pub fn unsupported(message: impl Into<String>) -> Self {
244 Error::new(ErrorCode::Unsupported, message)
245 }
246 pub fn cancelled(message: impl Into<String>) -> Self {
248 Error::new(ErrorCode::Cancelled, message)
249 }
250
251 fn ctx(&self) -> &ErrorContext {
252 match self {
253 Error::Config(c)
254 | Error::Authentication(c)
255 | Error::PermissionDenied(c)
256 | Error::NotFound(c)
257 | Error::Conflict(c)
258 | Error::RateLimited(c)
259 | Error::Validation(c)
260 | Error::Unavailable(c)
261 | Error::Timeout(c)
262 | Error::Unsupported(c)
263 | Error::Cancelled(c) => c,
264 }
265 }
266
267 fn ctx_mut(&mut self) -> &mut ErrorContext {
268 match self {
269 Error::Config(c)
270 | Error::Authentication(c)
271 | Error::PermissionDenied(c)
272 | Error::NotFound(c)
273 | Error::Conflict(c)
274 | Error::RateLimited(c)
275 | Error::Validation(c)
276 | Error::Unavailable(c)
277 | Error::Timeout(c)
278 | Error::Unsupported(c)
279 | Error::Cancelled(c) => c,
280 }
281 }
282
283 pub fn with_status(mut self, status: u16) -> Self {
285 self.ctx_mut().http_status = Some(status);
286 self
287 }
288 pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
290 self.ctx_mut().request_id = Some(request_id.into());
291 self
292 }
293 pub fn with_retryable(mut self, retryable: bool) -> Self {
295 self.ctx_mut().retryable = retryable;
296 self
297 }
298 pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
300 self.ctx_mut().retry_after = Some(retry_after);
301 self
302 }
303 pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
305 self.ctx_mut().source = Some(Arc::new(source));
306 self
307 }
308 pub fn with_message(mut self, message: impl Into<String>) -> Self {
310 self.ctx_mut().message = message.into();
311 self
312 }
313
314 pub fn code(&self) -> ErrorCode {
316 match self {
317 Error::Config(_) => ErrorCode::Config,
318 Error::Authentication(_) => ErrorCode::Authentication,
319 Error::PermissionDenied(_) => ErrorCode::PermissionDenied,
320 Error::NotFound(_) => ErrorCode::NotFound,
321 Error::Conflict(_) => ErrorCode::Conflict,
322 Error::RateLimited(_) => ErrorCode::RateLimited,
323 Error::Validation(_) => ErrorCode::Validation,
324 Error::Unavailable(_) => ErrorCode::Unavailable,
325 Error::Timeout(_) => ErrorCode::Timeout,
326 Error::Unsupported(_) => ErrorCode::Unsupported,
327 Error::Cancelled(_) => ErrorCode::Cancelled,
328 }
329 }
330 pub fn message(&self) -> &str {
332 &self.ctx().message
333 }
334 pub fn http_status(&self) -> Option<u16> {
336 self.ctx().http_status
337 }
338 pub fn request_id(&self) -> Option<&str> {
340 self.ctx().request_id.as_deref()
341 }
342 pub fn is_retryable(&self) -> bool {
344 self.ctx().retryable
345 }
346 pub fn retry_after(&self) -> Option<Duration> {
348 self.ctx().retry_after
349 }
350 pub fn is(&self, code: ErrorCode) -> bool {
352 self.code() == code
353 }
354 pub fn cause(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
356 self.ctx().source.as_deref()
357 }
358}
359
360impl fmt::Display for Error {
361 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
362 f.write_str(&self.ctx().message)
363 }
364}
365
366impl std::error::Error for Error {
367 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
368 self.ctx()
369 .source
370 .as_deref()
371 .map(|s| s as &(dyn std::error::Error + 'static))
372 }
373}
374
375impl From<serde_json::Error> for Error {
376 fn from(err: serde_json::Error) -> Self {
377 Error::validation(format!("invalid JSON: {}", err.classify_name())).with_source(err)
378 }
379}
380
381trait ClassifyName {
383 fn classify_name(&self) -> &'static str;
384}
385
386impl ClassifyName for serde_json::Error {
387 fn classify_name(&self) -> &'static str {
388 match self.classify() {
389 serde_json::error::Category::Io => "I/O error",
390 serde_json::error::Category::Syntax => "syntax error",
391 serde_json::error::Category::Data => "unexpected data",
392 serde_json::error::Category::Eof => "unexpected end of input",
393 }
394 }
395}