Skip to main content

sc_lint/
error.rs

1use crate::consts;
2use std::error::Error;
3use std::fmt;
4
5use serde::Serialize;
6use serde::ser::SerializeStruct;
7use serde_json::Map;
8use serde_json::Value;
9
10pub(crate) trait ErrorCode {
11    fn as_str(&self) -> &'static str;
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
15#[serde(rename_all = "snake_case")]
16pub enum CliErrorKind {
17    Usage,
18    Config,
19    Capability,
20    BackendFailure,
21    BackendProtocol,
22    Internal,
23}
24
25impl CliErrorKind {
26    pub const fn code(self) -> &'static str {
27        match self {
28            Self::Usage => "CLI.USAGE_ERROR",
29            Self::Config => "CLI.CONFIG_ERROR",
30            Self::Capability => "CLI.CAPABILITY_ERROR",
31            Self::BackendFailure => "CLI.BACKEND_EXEC_FAILURE",
32            Self::BackendProtocol => "CLI.BACKEND_PROTOCOL_ERROR",
33            Self::Internal => "CLI.INTERNAL_ERROR",
34        }
35    }
36
37    pub const fn exit_code(self) -> u8 {
38        match self {
39            Self::Usage => consts::EXIT_USAGE,
40            Self::Config => consts::EXIT_CONFIG,
41            Self::Capability => consts::EXIT_CAPABILITY,
42            Self::BackendFailure => consts::EXIT_BACKEND_FAILURE,
43            Self::BackendProtocol => consts::EXIT_BACKEND_PROTOCOL,
44            Self::Internal => consts::EXIT_INTERNAL,
45        }
46    }
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct CliError {
51    pub(crate) kind: CliErrorKind,
52    pub message: String,
53    pub details: Map<String, Value>,
54    pub cause: Option<String>,
55    pub suggested_action: Option<String>,
56    pub documentation: Option<String>,
57    code_override: Option<&'static str>,
58    source: Option<CliErrorSource>,
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
62struct CliErrorSource(String);
63
64impl fmt::Display for CliErrorSource {
65    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
66        formatter.write_str(&self.0)
67    }
68}
69
70impl Error for CliErrorSource {}
71
72impl Serialize for CliError {
73    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
74    where
75        S: serde::Serializer,
76    {
77        let field_count = 3
78            + usize::from(!self.details.is_empty())
79            + usize::from(self.cause.is_some())
80            + usize::from(self.suggested_action.is_some())
81            + usize::from(self.documentation.is_some());
82        let mut state = serializer.serialize_struct("CliError", field_count)?;
83        state.serialize_field(consts::FIELD_KIND, &self.kind)?;
84        state.serialize_field(consts::FIELD_CODE, self.code())?;
85        state.serialize_field(consts::FIELD_MESSAGE, &self.message)?;
86        if !self.details.is_empty() {
87            state.serialize_field(consts::FIELD_DETAILS, &self.details)?;
88        }
89        if let Some(cause) = self.cause.as_ref() {
90            state.serialize_field(consts::FIELD_CAUSE, cause)?;
91        }
92        if let Some(suggested_action) = self.suggested_action.as_ref() {
93            state.serialize_field(consts::FIELD_SUGGESTED_ACTION, suggested_action)?;
94        }
95        if let Some(documentation) = self.documentation.as_ref() {
96            state.serialize_field(consts::FIELD_DOCS, documentation)?;
97        }
98        state.end()
99    }
100}
101
102impl fmt::Display for CliError {
103    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
104        formatter.write_str(&self.message)
105    }
106}
107
108impl Error for CliError {
109    fn source(&self) -> Option<&(dyn Error + 'static)> {
110        self.source
111            .as_ref()
112            .map(|source| source as &(dyn Error + 'static))
113    }
114}
115
116impl CliError {
117    pub fn usage(message: impl Into<String>) -> Self {
118        Self::new(CliErrorKind::Usage, message)
119    }
120
121    pub fn config(message: impl Into<String>) -> Self {
122        Self::new(CliErrorKind::Config, message)
123    }
124
125    pub fn capability(message: impl Into<String>) -> Self {
126        Self::new(CliErrorKind::Capability, message)
127    }
128
129    pub fn backend_failure(message: impl Into<String>) -> Self {
130        Self::new(CliErrorKind::BackendFailure, message)
131    }
132
133    pub fn backend_protocol(message: impl Into<String>) -> Self {
134        Self::new(CliErrorKind::BackendProtocol, message)
135    }
136
137    pub fn internal(message: impl Into<String>) -> Self {
138        Self::new(CliErrorKind::Internal, message)
139    }
140
141    pub(crate) fn new(kind: CliErrorKind, message: impl Into<String>) -> Self {
142        Self {
143            kind,
144            message: message.into(),
145            details: Map::new(),
146            cause: None,
147            suggested_action: None,
148            documentation: None,
149            code_override: None,
150            source: None,
151        }
152    }
153
154    pub fn with_detail(mut self, key: impl Into<String>, value: Value) -> Self {
155        self.details.insert(key.into(), value);
156        self
157    }
158
159    pub fn with_suggested_action(mut self, suggested_action: impl Into<String>) -> Self {
160        self.suggested_action = Some(suggested_action.into());
161        self
162    }
163
164    pub fn with_documentation(mut self, documentation: impl Into<String>) -> Self {
165        self.documentation = Some(documentation.into());
166        self
167    }
168
169    pub const fn with_code(mut self, code: &'static str) -> Self {
170        self.code_override = Some(code);
171        self
172    }
173
174    pub fn with_cause(mut self, cause: impl Into<String>) -> Self {
175        let cause = cause.into();
176        self.cause = Some(cause.clone());
177        self.source = Some(CliErrorSource(cause));
178        self
179    }
180
181    pub fn with_source<E>(mut self, source: E) -> Self
182    where
183        E: fmt::Display,
184    {
185        // source erased to String — CliError is a display type, not a re-throw carrier
186        let cause = source.to_string();
187        self.cause = Some(cause.clone());
188        self.source = Some(CliErrorSource(cause));
189        self
190    }
191
192    pub fn kind_label(&self) -> &'static str {
193        match self.kind {
194            CliErrorKind::Usage => "usage",
195            CliErrorKind::Config => "config",
196            CliErrorKind::Capability => "capability",
197            CliErrorKind::BackendFailure => "backend_failure",
198            CliErrorKind::BackendProtocol => "backend_protocol",
199            CliErrorKind::Internal => "internal",
200        }
201    }
202
203    pub const fn exit_code(&self) -> u8 {
204        self.kind.exit_code()
205    }
206
207    pub const fn code(&self) -> &'static str {
208        match self.code_override {
209            Some(code) => code,
210            None => self.kind.code(),
211        }
212    }
213}