Skip to main content

nils_common/provider_runtime/
error.rs

1use thiserror::Error;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum CoreErrorCategory {
5    Config,
6    Auth,
7    Exec,
8    Dependency,
9    Validation,
10    Internal,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum ProviderCategoryHint {
15    Auth,
16    Dependency,
17    Validation,
18    Internal,
19}
20
21#[derive(Debug, Clone, PartialEq, Eq, Error)]
22#[error("{message}")]
23pub struct CoreError {
24    pub category: CoreErrorCategory,
25    pub code: &'static str,
26    pub message: String,
27    pub retryable: bool,
28}
29
30impl CoreError {
31    pub fn new(
32        category: CoreErrorCategory,
33        code: &'static str,
34        message: impl Into<String>,
35    ) -> Self {
36        Self {
37            category,
38            code,
39            message: message.into(),
40            retryable: false,
41        }
42    }
43
44    pub fn with_retryable(mut self, retryable: bool) -> Self {
45        self.retryable = retryable;
46        self
47    }
48
49    pub fn config(code: &'static str, message: impl Into<String>) -> Self {
50        Self::new(CoreErrorCategory::Config, code, message)
51    }
52
53    pub fn auth(code: &'static str, message: impl Into<String>) -> Self {
54        Self::new(CoreErrorCategory::Auth, code, message)
55    }
56
57    pub fn exec(code: &'static str, message: impl Into<String>) -> Self {
58        Self::new(CoreErrorCategory::Exec, code, message)
59    }
60
61    pub fn dependency(code: &'static str, message: impl Into<String>) -> Self {
62        Self::new(CoreErrorCategory::Dependency, code, message)
63    }
64
65    pub fn validation(code: &'static str, message: impl Into<String>) -> Self {
66        Self::new(CoreErrorCategory::Validation, code, message)
67    }
68
69    pub fn internal(code: &'static str, message: impl Into<String>) -> Self {
70        Self::new(CoreErrorCategory::Internal, code, message)
71    }
72
73    pub fn exit_code_hint(&self) -> i32 {
74        match self.category {
75            CoreErrorCategory::Validation | CoreErrorCategory::Config => 64,
76            CoreErrorCategory::Auth
77            | CoreErrorCategory::Exec
78            | CoreErrorCategory::Dependency
79            | CoreErrorCategory::Internal => 1,
80        }
81    }
82
83    pub fn provider_category_hint(&self) -> ProviderCategoryHint {
84        match self.category {
85            CoreErrorCategory::Auth => ProviderCategoryHint::Auth,
86            CoreErrorCategory::Dependency => ProviderCategoryHint::Dependency,
87            CoreErrorCategory::Validation | CoreErrorCategory::Config => {
88                ProviderCategoryHint::Validation
89            }
90            CoreErrorCategory::Exec | CoreErrorCategory::Internal => ProviderCategoryHint::Internal,
91        }
92    }
93}