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
use log::SetLoggerError;
use std::{error, fmt, result};
pub type Result<T> = result::Result<T, Error>;
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
UnknownError,
CLIError(String),
InvalidArgument(String),
UnexpectedDuplicate,
FileIOError(String),
ParsingError(String),
InvalidTarget(String),
BackEndError(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Error::CLIError(ref msg) => write!(f, "CLI Error: {}", msg),
Error::InvalidArgument(ref msg) => write!(f, "Invalid argument: {}", msg),
Error::UnexpectedDuplicate => write!(f, "Unexpected duplicate"),
Error::UnknownError => write!(f, "Unknown error"),
Error::FileIOError(ref msg) => write!(f, "File I/O error: {}", msg),
Error::ParsingError(ref msg) => write!(f, "Parsing error: {}", msg),
Error::InvalidTarget(ref msg) => write!(f, "Invalid target: {}", msg),
Error::BackEndError(ref msg) => write!(f, "Back-end error: {}", msg),
}
}
}
impl error::Error for Error {}
impl From<Box<dyn error::Error>> for Error {
fn from(error: Box<dyn error::Error>) -> Self {
if let Ok(error) = error.downcast::<Self>() {
*error
} else {
Error::UnknownError
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::FileIOError(e.to_string())
}
}
impl From<SetLoggerError> for Error {
fn from(e: SetLoggerError) -> Self {
Error::CLIError(e.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error() {
let a = Error::InvalidArgument("test".to_string());
let b = Error::UnexpectedDuplicate;
assert_eq!(a.to_string(), "Invalid argument: test");
assert_eq!(b.to_string(), "Unexpected duplicate");
}
}