frequenz_microgrid_component_graph/
error.rs

1// License: MIT
2// Copyright © 2024 Frequenz Energy-as-a-Service GmbH
3
4//! This module defines the `Error` struct and the `ErrorKind` enum, which are
5//! used to represent errors that can occur in the library.
6
7/// A macro for defining the `ErrorKind` enum, the `Display` implementation for
8/// it, and the constructors for the `Error` struct.
9macro_rules! ErrorKind {
10    ($(
11        ($kind:ident, $ctor:ident)
12    ),*) => {
13        /// The kind of error that occurred.
14        #[derive(Debug, Clone, PartialEq)]
15        pub(crate) enum ErrorKind {
16            $(
17                $kind,
18            )*
19        }
20
21        impl std::fmt::Display for ErrorKind {
22            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23                match self {
24                    $(
25                        Self::$kind => write!(f, "{}", stringify!($kind)),
26                    )*
27                }
28            }
29        }
30
31        /// Constructors for [`Error`].
32        impl Error {
33            $(
34                #[doc = concat!(
35                    "Creates a new [`Error`] with the `",
36                    stringify!($kind),
37                    "` kind and the given description."
38                )]
39                pub(crate) fn $ctor(desc: impl Into<String>) -> crate::Error {
40                    Self {
41                        kind: ErrorKind::$kind,
42                        desc: desc.into(),
43                    }
44                }
45            )*
46        }
47    };
48}
49
50ErrorKind!(
51    (ComponentNotFound, component_not_found),
52    (Internal, internal),
53    (InvalidComponent, invalid_component),
54    (InvalidConnection, invalid_connection),
55    (InvalidGraph, invalid_graph)
56);
57
58/// An error that can occur during the creation or traversal of a
59/// [ComponentGraph][crate::ComponentGraph].
60#[derive(Debug, Clone, PartialEq)]
61pub struct Error {
62    kind: ErrorKind,
63    desc: String,
64}
65
66impl std::fmt::Display for Error {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        write!(f, "{}: {}", self.kind, self.desc)
69    }
70}
71
72impl std::error::Error for Error {}