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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
use backtrace::Backtrace;
use serde::Deserialize;
use serde::Serialize;
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
pub struct AnyError {
typ: Option<String>,
msg: String,
source: Option<Box<AnyError>>,
context: Vec<String>,
backtrace: Option<String>,
}
impl Display for AnyError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
if let Some(t) = &self.typ {
write!(f, "{}: ", t)?;
}
write!(f, "{}", self.msg)?;
if let Some(ref s) = self.source {
write!(f, " source: {}", s)?;
}
for (i, ctx) in self.context.iter().enumerate() {
if i > 0 {
write!(f, ",")?;
}
write!(f, " while: {}", ctx)?;
}
Ok(())
}
}
impl std::fmt::Debug for AnyError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
<Self as Display>::fmt(self, f)?;
if let Some(ref b) = self.backtrace {
write!(f, "\nbacktrace:\n{}", b)?;
}
Ok(())
}
}
impl std::error::Error for AnyError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match &self.source {
Some(x) => Some(x.as_ref()),
None => None,
}
}
}
#[cfg(feature = "anyhow")]
impl From<anyhow::Error> for AnyError {
fn from(a: anyhow::Error) -> Self {
AnyError::from_dyn(a.as_ref(), None)
}
}
impl AnyError {
pub fn error(msg: impl ToString) -> Self {
Self {
typ: None,
msg: msg.to_string(),
source: None,
context: vec![],
backtrace: None,
}
}
pub fn new<E>(e: &E) -> Self
where E: Error + 'static {
let q: &(dyn Error + 'static) = e;
let x = q.downcast_ref::<AnyError>();
let typ = match x {
Some(ae) => ae.typ.clone(),
None => Some(std::any::type_name::<E>().to_string()),
};
Self::from_dyn(e, typ)
}
pub fn from_dyn(e: &(dyn Error + 'static), typ: Option<String>) -> Self {
let x = e.downcast_ref::<AnyError>();
return match x {
Some(ae) => ae.clone(),
None => {
let bt = e.backtrace().map(|b| format!("{:?}", b));
let source = e.source().map(|x| Box::new(AnyError::from_dyn(x, None)));
Self {
typ,
msg: e.to_string(),
source,
context: vec![],
backtrace: bt,
}
}
};
}
#[must_use]
pub fn with_backtrace(mut self) -> Self {
if self.backtrace.is_some() {
return self;
}
self.backtrace = Some(format!("{:?}", Backtrace::new()));
self
}
#[must_use]
pub fn add_context<D: Display, F: FnOnce() -> D>(mut self, ctx: F) -> Self {
self.context.push(format!("{}", ctx()));
self
}
pub fn get_type(&self) -> Option<&str> {
self.typ.as_ref().map(|x| x as _)
}
pub fn backtrace(&self) -> Option<&str> {
self.backtrace.as_ref().map(|x| x as _)
}
}