frequenz_microgrid_component_graph/
error.rs1#[derive(Debug, Clone, PartialEq)]
15#[non_exhaustive]
16pub enum ErrorKind {
17 ComponentNotFound,
19
20 Internal,
22
23 InvalidComponent,
26
27 InvalidConnection,
29
30 InvalidGraph,
33
34 ValidationErrors(Vec<ValidationError>),
37}
38
39impl std::fmt::Display for ErrorKind {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 let name = match self {
42 Self::ComponentNotFound => "ComponentNotFound",
43 Self::Internal => "Internal",
44 Self::InvalidComponent => "InvalidComponent",
45 Self::InvalidConnection => "InvalidConnection",
46 Self::InvalidGraph => "InvalidGraph",
47 Self::ValidationErrors(_) => "ValidationErrors",
48 };
49 f.write_str(name)
50 }
51}
52
53#[derive(Debug, Clone, PartialEq)]
56pub struct Error {
57 kind: ErrorKind,
58 desc: String,
59}
60
61impl Error {
62 pub fn kind(&self) -> &ErrorKind {
64 &self.kind
65 }
66
67 pub(crate) fn into_validation_errors(self) -> Result<Vec<ValidationError>, Error> {
73 match self.kind {
74 ErrorKind::ValidationErrors(errors) => Ok(errors),
75 kind => Err(Error {
76 kind,
77 desc: self.desc,
78 }),
79 }
80 }
81}
82
83impl Error {
85 pub(crate) fn component_not_found(desc: impl Into<String>) -> Self {
88 Self {
89 kind: ErrorKind::ComponentNotFound,
90 desc: desc.into(),
91 }
92 }
93
94 pub(crate) fn internal(desc: impl Into<String>) -> Self {
97 Self {
98 kind: ErrorKind::Internal,
99 desc: desc.into(),
100 }
101 }
102
103 pub(crate) fn invalid_component(desc: impl Into<String>) -> Self {
106 Self {
107 kind: ErrorKind::InvalidComponent,
108 desc: desc.into(),
109 }
110 }
111
112 pub(crate) fn invalid_connection(desc: impl Into<String>) -> Self {
115 Self {
116 kind: ErrorKind::InvalidConnection,
117 desc: desc.into(),
118 }
119 }
120
121 pub(crate) fn invalid_graph(desc: impl Into<String>) -> Self {
124 Self {
125 kind: ErrorKind::InvalidGraph,
126 desc: desc.into(),
127 }
128 }
129
130 pub(crate) fn validation_errors(errors: Vec<ValidationError>) -> Self {
133 Self {
136 kind: ErrorKind::ValidationErrors(errors),
137 desc: String::new(),
138 }
139 }
140}
141
142impl std::fmt::Display for Error {
143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144 match &self.kind {
145 ErrorKind::ValidationErrors(errors) => {
146 write!(f, "Graph validation failed:")?;
147 for error in errors {
148 write!(f, "\n {error}")?;
149 }
150 Ok(())
151 }
152 kind => write!(f, "{kind}: {}", self.desc),
153 }
154 }
155}
156
157impl std::error::Error for Error {}
158
159#[derive(Debug, Clone, PartialEq)]
168pub struct ValidationError {
169 message: String,
170 component_ids: Vec<u64>,
171}
172
173impl ValidationError {
174 pub(crate) fn new(message: impl Into<String>, component_ids: impl Into<Vec<u64>>) -> Self {
177 Self {
178 message: message.into(),
179 component_ids: component_ids.into(),
180 }
181 }
182
183 pub fn message(&self) -> &str {
185 &self.message
186 }
187
188 pub fn component_ids(&self) -> &[u64] {
190 &self.component_ids
191 }
192}
193
194impl std::fmt::Display for ValidationError {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 f.write_str(&self.message)
197 }
198}
199
200impl std::error::Error for ValidationError {}
201
202impl From<ValidationError> for Error {
203 fn from(error: ValidationError) -> Self {
204 Error::validation_errors(vec![error])
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 #[test]
213 fn validation_error_exposes_its_message_and_components() {
214 let error = ValidationError::new("boom", [3u64, 4]);
215 assert_eq!(error.message(), "boom");
216 assert_eq!(error.component_ids(), &[3, 4]);
217 assert_eq!(error.to_string(), "boom");
219 }
220
221 #[test]
222 fn leaf_error_display_is_unchanged() {
223 assert_eq!(
224 Error::invalid_graph("No grid component found.").to_string(),
225 "InvalidGraph: No grid component found."
226 );
227 }
228
229 #[test]
230 fn validation_errors_display_lists_each_failure() {
231 let error = Error::validation_errors(vec![
232 ValidationError::new("first problem", [1u64]),
233 ValidationError::new("second problem", [2u64, 3]),
234 ]);
235 assert_eq!(
236 error.to_string(),
237 "Graph validation failed:\n first problem\n second problem"
238 );
239 }
240
241 #[test]
242 fn into_validation_errors_unwraps_the_collected_failures() {
243 let error: Error = ValidationError::new("boom", [1u64]).into();
244 assert_eq!(
245 error.into_validation_errors(),
246 Ok(vec![ValidationError::new("boom", [1u64])])
247 );
248 }
249
250 #[test]
251 fn into_validation_errors_passes_other_kinds_through() {
252 assert_eq!(
253 Error::internal("bug").into_validation_errors(),
254 Err(Error::internal("bug"))
255 );
256 }
257}