1use powerio_core::{DiagnosticInfo, ErrorCategory};
2use thiserror::Error;
3
4use crate::diagnostics::codes;
5
6pub type Result<T> = std::result::Result<T, Error>;
7
8#[derive(Debug, Error)]
9#[non_exhaustive]
10pub enum Error {
11 #[error("io error reading {path}: {source}")]
12 Io {
13 path: String,
14 #[source]
15 source: std::io::Error,
16 },
17
18 #[error("malformed {format} JSON: {message}")]
19 Json {
20 format: &'static str,
21 message: String,
22 },
23
24 #[error("{format} read error: {message}")]
25 FormatRead {
26 format: &'static str,
27 message: String,
28 },
29
30 #[error(
31 "unknown distribution format `{0}` (expected dss, pmd, pmd-math, bmopf, cim-dist, gridlabd, or ravens-json)"
32 )]
33 UnknownFormat(String),
34
35 #[error("neutral Kron reduction failed: {message}")]
36 KronReduction { message: String },
37
38 #[error("LinDist3Flow preparation failed: {message}")]
39 LinDist3FlowPreparation { message: String },
40}
41
42impl Error {
43 #[must_use]
46 pub fn code(&self) -> &'static DiagnosticInfo {
47 match self {
48 Error::Io { .. } => &codes::READ_DIST_IO_FAILED,
49 Error::Json { .. } => &codes::PARSE_DIST_MALFORMED,
50 Error::FormatRead { .. } => &codes::PARSE_DIST_SOURCE_MALFORMED,
51 Error::UnknownFormat(_) => &codes::REQUEST_DIST_FORMAT_UNKNOWN,
52 Error::KronReduction { .. } => &codes::TRANSFORM_DIST_KRON_REDUCTION_FAILED,
53 Error::LinDist3FlowPreparation { .. } => {
54 &codes::TRANSFORM_DIST_LINDIST3FLOW_PREPARATION_FAILED
55 }
56 }
57 }
58
59 #[must_use]
61 pub fn category(&self) -> ErrorCategory {
62 match self {
63 Error::Io { .. } => ErrorCategory::Io,
64 Error::Json { .. } | Error::FormatRead { .. } => ErrorCategory::Parse,
65 Error::UnknownFormat(_) => ErrorCategory::Request,
66 Error::KronReduction { .. } | Error::LinDist3FlowPreparation { .. } => {
67 ErrorCategory::Data
68 }
69 }
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76
77 #[test]
78 fn every_error_code_publishes_the_category_the_variant_reports() {
79 let every = [
80 Error::Io {
81 path: "case.dss".into(),
82 source: std::io::Error::from(std::io::ErrorKind::NotFound),
83 },
84 Error::Json {
85 format: "BMOPF",
86 message: "top level is not an object".into(),
87 },
88 Error::FormatRead {
89 format: "case text",
90 message: "not valid UTF-8".into(),
91 },
92 Error::UnknownFormat("xyz".into()),
93 Error::KronReduction {
94 message: "ambiguous neutral".into(),
95 },
96 Error::LinDist3FlowPreparation {
97 message: "unsupported transformer".into(),
98 },
99 ];
100 for error in &every {
101 assert_eq!(
102 error.code().category,
103 Some(error.category()),
104 "{}",
105 error.code().code
106 );
107 }
108 }
109}