1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Look here for an example on how to implement error types: https://doc.rust-lang.org/src/std/io/error.rs.html#42
use std::error;
use std::error::Error;
use std::fmt;

#[derive(Debug)]
pub struct OtherError {
    error_type: OtherErrorType,
    explanation: String,
    source: Option<OtherErrorSource>,
}

#[derive(Debug)]
pub enum OtherErrorSource {
    Display(std::fmt::Error),
}

#[derive(Debug, Clone, PartialEq)]
pub enum OtherErrorType {
    Display,
    Other,
}

impl OtherError {
    pub fn new(
        error_type: OtherErrorType,
        explanation: String,
        source: Option<OtherErrorSource>,
    ) -> Self {
        Self {
            error_type,
            explanation,
            source,
        }
    }

    pub fn error_type(&self) -> OtherErrorType {
        self.error_type.to_owned()
    }
    pub fn explanation(&self) -> String {
        self.explanation.to_owned()
    }
}

impl error::Error for OtherError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self.source {
            Some(ref error) => match error {
                OtherErrorSource::Display(error) => Some(error),
            },
            None => None,
        }
    }
}

impl fmt::Display for OtherError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.error_type {
            // LogicErrorType::GraphBlas(_err) => writeln!(f, "Context:\n{}", &self.context)?,
            _ => writeln!(f, "Explanation:\n{}", &self.explanation)?,
        };

        match &self.source() {
            Some(err) => writeln!(f, "Source error:\n{}", err)?,
            &None => (),
        }
        Ok(())
    }
}

impl From<std::fmt::Error> for OtherError {
    fn from(error: std::fmt::Error) -> Self {
        Self {
            error_type: OtherErrorType::Display,
            explanation: String::new(),
            source: Some(OtherErrorSource::Display(error)),
        }
    }
}