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
pub use af_core_macros::{fail, fail_err as err, fail_when as when, fail_wrap as wrap};
use crate::prelude::*;
use crate::string::SharedString;
#[derive(Clone)]
pub struct Error {
message: SharedString,
trace: im::Vector<SharedString>,
}
pub type Result<T = (), E = Error> = std::result::Result<T, E>;
pub fn from<T: Into<Error>>(err: T) -> Error {
err.into()
}
impl Error {
pub fn new(message: impl Into<SharedString>) -> Self {
Self { message: message.into(), trace: default() }
}
pub fn set_cause(&mut self, cause: impl Into<Self>) {
let cause = cause.into();
self.trace = cause.trace;
self.trace.push_front(cause.message);
}
pub fn with_cause(mut self, cause: impl Into<Self>) -> Self {
self.set_cause(cause);
self
}
}
impl<T> From<T> for Error
where
T: std::error::Error,
{
fn from(err: T) -> Self {
Self::new(err.to_string())
}
}
impl Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.message, f)
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.message, f)?;
if f.alternate() {
for err in &self.trace {
write!(f, "\n * {:#}", fmt::indent("", " ", err))?;
}
}
Ok(())
}
}