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
use serde_json::Error as JsonError;
use serde_yaml::Error as YamlError;
use std::fmt;
use std::io::Error as IoError;

#[derive(Debug)]
pub enum GenError {
    IoError(IoError),
    JsonError(JsonError),
    YamlError(YamlError),
    WrongFileExtension(Option<String>),
}

impl From<IoError> for GenError {
    fn from(e: IoError) -> GenError {
        GenError::IoError(e)
    }
}

impl From<JsonError> for GenError {
    fn from(e: JsonError) -> GenError {
        GenError::JsonError(e)
    }
}

impl From<YamlError> for GenError {
    fn from(e: YamlError) -> GenError {
        GenError::YamlError(e)
    }
}

impl fmt::Display for GenError {
    fn fmt<'a>(&self, f: &mut fmt::Formatter<'a>) -> Result<(), fmt::Error> {
        match self {
            GenError::IoError(e) => write!(f, "Io error occurred: {}", e),
            GenError::JsonError(e) => write!(f, "Json deserialization error occurred: {}", e),
            GenError::YamlError(e) => write!(f, "Yaml deserialization error occurred: {}", e),
            GenError::WrongFileExtension(o) => {
                if let Some(s) = o {
                    write!(f, "Bad file type: {}", s)
                } else {
                    write!(f, "Bad file type")
                }
            }
        }
    }
}

impl std::error::Error for GenError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            GenError::IoError(e) => Some(e),
            GenError::JsonError(e) => Some(e),
            GenError::YamlError(e) => Some(e),
            GenError::WrongFileExtension(_) => None,
        }
    }
}