simpleg_core/
error.rs

1use std::fmt::{Debug, Display, Formatter};
2
3use crate::error_kind::SERIALIZATION_FAILURE;
4
5#[macro_export]
6macro_rules! ok_or_return_error {
7    ($statement: expr, $error_kind: expr, $error_message: expr) => {
8        match $statement {
9            Ok(value) => value,
10            Err(error) => {
11                return Err(Error::new(
12                    $error_kind,
13                    format!("{}: {}", $error_message, error),
14                ))
15            }
16        }
17    };
18}
19
20#[macro_export]
21macro_rules! some_or_return_error {
22    ($statement: expr, $error_kind: expr, $error_message: expr) => {
23        match $statement {
24            Some(value) => value,
25            None => return Err(Error::new($error_kind, $error_message)),
26        }
27    };
28}
29
30pub struct Error {
31    kind: String,
32    message: String,
33}
34
35impl Error {
36    pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
37        Self {
38            kind: kind.into(),
39            message: message.into(),
40        }
41    }
42}
43
44impl Debug for Error {
45    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
46        write!(f, "{}: {}", self.kind, self.message)
47    }
48}
49
50impl Display for Error {
51    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
52        write!(f, "{}: {}", self.kind, self.message)
53    }
54}
55
56impl std::error::Error for Error {
57    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
58        None
59    }
60
61    fn description(&self) -> &str {
62        &self.message
63    }
64
65    fn cause(&self) -> Option<&dyn std::error::Error> {
66        None
67    }
68}
69
70impl From<serde_json::Error> for Error {
71    fn from(error: serde_json::Error) -> Self {
72        Self::new(SERIALIZATION_FAILURE, error.to_string())
73    }
74}