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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
use std::error::Error as StdError;
use std::fmt;
#[derive(Debug, Eq, PartialEq)]
pub enum ErrorKind {
FsError,
Common(String),
WriteFailed,
ReadFailed,
RemoveFailed,
ParseError,
InvalidOperation,
InvalidPath,
InvalidBytesSize,
Other,
}
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
cause: Option<Box<dyn StdError + Send + Sync>>,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg = match &self.kind {
ErrorKind::FsError => "fs error".to_string(),
ErrorKind::Common(s) => s.clone(),
ErrorKind::WriteFailed => "unable to write to a control group file".to_string(),
ErrorKind::ReadFailed => "unable to read a control group file".to_string(),
ErrorKind::RemoveFailed => "unable to remove a control group".to_string(),
ErrorKind::ParseError => "unable to parse control group file".to_string(),
ErrorKind::InvalidOperation => "the requested operation is invalid".to_string(),
ErrorKind::InvalidPath => "the given path is invalid".to_string(),
ErrorKind::InvalidBytesSize => "invalid bytes size".to_string(),
ErrorKind::Other => "an unknown error".to_string(),
};
if let Some(cause) = &self.cause {
write!(f, "{} caused by: {:?}", msg, cause)
} else {
write!(f, "{}", msg)
}
}
}
impl StdError for Error {
fn cause(&self) -> Option<&dyn StdError> {
match self.cause {
Some(ref x) => Some(&**x),
None => None,
}
}
}
impl Error {
pub(crate) fn from_string(s: String) -> Self {
Self {
kind: ErrorKind::Common(s),
cause: None,
}
}
pub(crate) fn new(kind: ErrorKind) -> Self {
Self { kind, cause: None }
}
pub(crate) fn with_cause<E>(kind: ErrorKind, cause: E) -> Self
where
E: 'static + Send + Sync + StdError,
{
Self {
kind,
cause: Some(Box::new(cause)),
}
}
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
}
pub type Result<T> = ::std::result::Result<T, Error>;