Skip to main content

sz_configtool_lib/
error.rs

1use std::fmt;
2
3/// Custom error type for configuration operations
4#[derive(Debug)]
5pub enum SzConfigError {
6    /// JSON parsing error
7    JsonParse(String),
8    /// Item not found
9    NotFound(String), // Generic not found with description
10    /// Item already exists
11    AlreadyExists(String), // Generic already exists with description
12    /// Invalid input
13    InvalidInput(String),
14    /// Missing required section
15    MissingSection(String),
16    /// Invalid configuration structure
17    InvalidStructure(String),
18    /// Missing required field
19    MissingField(String),
20    /// Invalid configuration state
21    InvalidConfig(String),
22    /// Not implemented
23    NotImplemented(String),
24}
25
26impl SzConfigError {
27    /// Create a JSON parse error
28    pub fn json_parse<S: Into<String>>(msg: S) -> Self {
29        Self::JsonParse(msg.into())
30    }
31
32    /// Create a not found error
33    pub fn not_found<S: Into<String>>(msg: S) -> Self {
34        Self::NotFound(msg.into())
35    }
36
37    /// Create an already exists error
38    pub fn already_exists<S: Into<String>>(msg: S) -> Self {
39        Self::AlreadyExists(msg.into())
40    }
41
42    /// Create an invalid input error (validation)
43    pub fn validation<S: Into<String>>(msg: S) -> Self {
44        Self::InvalidInput(msg.into())
45    }
46
47    /// Create a not implemented error
48    pub fn not_implemented<S: Into<String>>(msg: S) -> Self {
49        Self::NotImplemented(msg.into())
50    }
51}
52
53impl fmt::Display for SzConfigError {
54    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55        match self {
56            Self::JsonParse(msg) => write!(f, "JSON parse error: {msg}"),
57            Self::NotFound(msg) => write!(f, "{msg}"),
58            Self::AlreadyExists(msg) => write!(f, "{msg}"),
59            Self::InvalidInput(msg) => write!(f, "Invalid input: {msg}"),
60            Self::MissingSection(section) => write!(f, "Missing config section: {section}"),
61            Self::InvalidStructure(msg) => write!(f, "Invalid config structure: {msg}"),
62            Self::MissingField(field) => write!(f, "Missing required field: {field}"),
63            Self::InvalidConfig(msg) => write!(f, "Invalid configuration: {msg}"),
64            Self::NotImplemented(msg) => write!(f, "Not implemented: {msg}"),
65        }
66    }
67}
68
69impl std::error::Error for SzConfigError {}
70
71impl From<serde_json::Error> for SzConfigError {
72    fn from(err: serde_json::Error) -> Self {
73        SzConfigError::JsonParse(err.to_string())
74    }
75}
76
77/// Result type for configuration operations
78pub type Result<T> = std::result::Result<T, SzConfigError>;