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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use csv;
use rusqlite;
use std::error::Error;
use std::fmt;
use std::io;

#[derive(Debug)]
pub enum ThprError {
    Generic(String),
    BadQuery(String),
    Csv(csv::Error),
    Io(io::Error),
    Rusqlite(rusqlite::Error),
}

impl fmt::Display for ThprError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ThprError::Generic(ref msg) => write!(f, "ThprError::Generic: {}", msg),
            ThprError::BadQuery(ref msg) => write!(f, "ThprError::BadQuery: {}", msg),
            ThprError::Io(ref err) => write!(f, "ThprError::Io: {}", err),
            ThprError::Csv(ref err) => write!(f, "ThprError::Csv: {}", err),
            ThprError::Rusqlite(ref err) => write!(f, "ThprError::Rusqlite: {}", err),
        }
    }
}
impl Error for ThprError {}

impl <'a> From<&'a str> for ThprError {
    fn from(message: &'a str) -> Self {
        ThprError::Generic(message.to_owned())
    }
}
impl <'a> From<&'a str> for Box<ThprError> {
    fn from(message: &'a str) -> Self {
        Box::new(ThprError::from(message))
    }
}

impl From<String> for Box<ThprError> {
    fn from(message: String) -> Self {
        Box::new(ThprError::Generic(message))
    }
}

impl From<csv::Error> for ThprError {
    fn from(csv_error: csv::Error) -> Self {
        ThprError::Csv(csv_error)
    }
}
impl From<csv::Error> for Box<ThprError> {
    fn from(csv_error: csv::Error) -> Self {
        Box::new(ThprError::from(csv_error))
    }
}

impl From<io::Error> for ThprError {
    fn from(io_error: io::Error) -> Self {
        ThprError::Io(io_error)
    }
}
impl From<io::Error> for Box<ThprError> {
    fn from(io_error: io::Error) -> Self {
        Box::new(ThprError::from(io_error))
    }
}

impl From<rusqlite::Error> for ThprError {
    fn from(rusqlite_error: rusqlite::Error) -> Self {
        ThprError::Rusqlite(rusqlite_error)
    }
}
impl From<rusqlite::Error> for Box<ThprError> {
    fn from(rusqlite_error: rusqlite::Error) -> Self {
        Box::new(ThprError::from(rusqlite_error))
    }
}

pub type ThprResult<T> = Result<T, Box<ThprError>>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_autoconvert_string_to_thpr_error() {
        let _: ThprResult<()> = Err("This is a generic error message".into());
    }

    #[test]
    fn test_thpr_error_is_error() {
        let _: Box<Error> = Box::new(ThprError::Generic("Some error".into()));
    }
}