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
#[cfg(feature = "chrono")]
use chrono;
use failure::{Backtrace, Context, Fail};
use std::{
fmt::{self, Display},
io,
str::Utf8Error,
};
use toml;
#[derive(Debug)]
pub struct Error {
inner: Context<ErrorKind>,
description: String,
}
impl Error {
pub fn new<S: ToString>(kind: ErrorKind, description: &S) -> Self {
Self {
inner: Context::new(kind),
description: description.to_string(),
}
}
pub fn kind(&self) -> ErrorKind {
*self.inner.get_context()
}
}
impl Fail for Error {
fn cause(&self) -> Option<&Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: {}", &self.inner, &self.description)
}
}
#[derive(Copy, Clone, Debug, Eq, Fail, PartialEq)]
pub enum ErrorKind {
#[fail(display = "bad parameter")]
BadParam,
#[fail(display = "I/O operation failed")]
Io,
#[fail(display = "couldn't parse data")]
Parse,
}
macro_rules! err {
($kind:path, $msg:expr) => {
crate::error::Error::new(
$kind,
&$msg.to_string()
)
};
($kind:path, $fmt:expr, $($arg:tt)+) => {
err!($kind, &format!($fmt, $($arg)+))
};
}
#[allow(unused_macros)]
macro_rules! fail {
($kind:path, $msg:expr) => {
return Err(err!($kind, $msg).into());
};
($kind:path, $fmt:expr, $($arg:tt)+) => {
fail!($kind, &format!($fmt, $($arg)+));
};
}
impl From<Utf8Error> for Error {
fn from(other: Utf8Error) -> Self {
err!(ErrorKind::Parse, &other)
}
}
#[cfg(feature = "chrono")]
impl From<chrono::ParseError> for Error {
fn from(other: chrono::ParseError) -> Self {
err!(ErrorKind::Parse, &other)
}
}
impl From<fmt::Error> for Error {
fn from(other: fmt::Error) -> Self {
err!(ErrorKind::Io, &other)
}
}
impl From<io::Error> for Error {
fn from(other: io::Error) -> Self {
err!(ErrorKind::Io, &other)
}
}
impl From<toml::de::Error> for Error {
fn from(other: toml::de::Error) -> Self {
err!(ErrorKind::Parse, &other)
}
}