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
113
114
115
116
117
118
|
use std::fmt;
pub type AardvarkResult<T> = Result<T, AardvarkError>;
#[derive(Debug)]
pub enum AardvarkError {
Message(String),
IOError(std::io::Error),
Chain(String, Box<Self>),
List(AardvarkErrorList),
ResolvConfParseError(resolv_conf::ParseError),
}
impl AardvarkError {
pub fn msg<S>(msg: S) -> Self
where
S: Into<String>,
{
Self::Message(msg.into())
}
pub fn wrap<S>(msg: S, chained: Self) -> Self
where
S: Into<String>,
{
Self::Chain(msg.into(), Box::new(chained))
}
}
pub trait AardvarkWrap<T, E> {
/// Wrap the error value with additional context.
fn wrap<C>(self, context: C) -> AardvarkResult<T>
where
C: Into<String>,
E: Into<AardvarkError>;
}
impl<T, E> AardvarkWrap<T, E> for Result<T, E>
where
E: Into<AardvarkError>,
{
fn wrap<C>(self, msg: C) -> AardvarkResult<T>
where
C: Into<String>,
E: Into<AardvarkError>,
{
// Not using map_err to save 2 useless frames off the captured backtrace
// in ext_context.
match self {
Ok(ok) => Ok(ok),
Err(error) => Err(AardvarkError::wrap(msg, error.into())),
}
}
}
impl fmt::Display for AardvarkError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Message(s) => write!(f, "{s}"),
Self::Chain(s, e) => write!(f, "{s}: {e}"),
Self::IOError(e) => write!(f, "IO error: {e}"),
Self::ResolvConfParseError(e) => write!(f, "parse resolv.conf: {e}"),
Self::List(list) => {
// some extra code to only add \n when it contains multiple errors
let mut iter = list.0.iter();
if let Some(first) = iter.next() {
write!(f, "{first}")?;
}
for err in iter {
write!(f, "\n{err}")?;
}
Ok(())
}
}
}
}
impl From<std::io::Error> for AardvarkError {
fn from(err: std::io::Error) -> Self {
Self::IOError(err)
}
}
impl From<nix::Error> for AardvarkError {
fn from(err: nix::Error) -> Self {
Self::IOError(err.into())
}
}
impl From<resolv_conf::ParseError> for AardvarkError {
fn from(err: resolv_conf::ParseError) -> Self {
Self::ResolvConfParseError(err)
}
}
#[derive(Debug)]
pub struct AardvarkErrorList(Vec<AardvarkError>);
impl AardvarkErrorList {
pub fn new() -> Self {
Self(vec![])
}
pub fn push(&mut self, err: AardvarkError) {
self.0.push(err)
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
// we do not need it but clippy wants it
impl Default for AardvarkErrorList {
fn default() -> Self {
Self::new()
}
}
|