system_harness/
error.rs

1use core::fmt::Display;
2use std::error;
3
4/// Type of error
5#[derive(Copy, Clone, Debug, PartialEq)]
6pub enum ErrorKind {
7    /// System is already running
8    AlreadyRunning,
9
10    /// System monitoring error
11    HarnessError,
12
13    /// Error connecting to pipe
14    PipeError,
15
16    /// Error while serializing data
17    SerializationError,
18
19    /// General I/O errors
20    IO,
21}
22
23/// System harness error
24#[derive(Debug)]
25#[allow(dead_code)]
26pub struct Error {
27    kind: ErrorKind,
28    error: Box<dyn error::Error + Send + Sync>,
29}
30
31impl Display for Error {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        write!(f, "{}", self.error.to_string())
34    }
35}
36
37impl Error {
38    pub fn new<E: Into<Box<dyn error::Error + Send + Sync>>>(kind: ErrorKind, error: E) -> Self {
39        Self {
40            kind,
41            error: error.into(),
42        }
43    }
44
45    pub fn kind(&self) -> ErrorKind {
46        self.kind
47    }
48}
49
50impl From<std::io::Error> for Error {
51    fn from(error: std::io::Error) -> Self {
52        Self::new(ErrorKind::IO, error)
53    }
54}
55
56impl From<std::ffi::NulError> for Error {
57    fn from(error: std::ffi::NulError) -> Self {
58        Self::new(ErrorKind::IO, error)
59    }
60}
61
62impl From<serde_json::Error> for Error {
63    fn from(error: serde_json::Error) -> Self {
64        Self::new(ErrorKind::IO, error)
65    }
66}
67
68impl From<std::str::Utf8Error> for Error {
69    fn from(error: std::str::Utf8Error) -> Self {
70        Self::new(ErrorKind::IO, error)
71    }
72}
73
74#[cfg(feature = "serde")]
75impl std::error::Error for Error {}
76
77#[cfg(feature = "serde")]
78impl serde::ser::Error for Error {
79    fn custom<T>(msg: T) -> Self
80    where
81        T: Display,
82    {
83        Self {
84            kind: ErrorKind::SerializationError,
85            error: std::io::Error::new(std::io::ErrorKind::Other, format!("{msg}")).into(),
86        }
87    }
88}