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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
use std::fmt::{Debug, Display, Formatter};
/// Represents an error.
#[derive(Debug)]
pub struct Error {
/// Detail information of the error.
detail: Detail,
}
/// The detail information of an error.
enum Detail {
/// An error that only contains the `ErrorKind`.
Simple(ErrorKind),
/// An error that contains the `ErrorKind` and extra information.
Custom(Box<Custom>),
}
/// Represents a custom error.
#[derive(Debug)]
pub struct Custom {
/// Type of error.
kind: ErrorKind,
/// Extra information about the error.
error: Box<dyn std::error::Error + Send + Sync>,
}
/// A list of general errors.
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
pub enum ErrorKind {
/// The value overflow.
Overflow,
/// The value is zero.
Zero,
/// The value is `Not a Number`.
NAN,
/// The provided input is invalid.
InvalidInput,
/// The provided number of arguments is invalid.
InvalidArgumentCount,
/// Performed a division by zero.
DivisionByZero,
/// The value is negative.
NegativeValue,
/// The value is positive.
PositiveValue,
/// The expression is invalid.
InvalidExpression,
/// The expression is empty.
Empty,
/// An unknown error.
Unknown,
}
impl ErrorKind {
/// Gets a `&str` representation of the `ErrorKind`.
pub fn as_str(&self) -> &'static str {
match *self {
ErrorKind::Overflow => "Value has overflow",
ErrorKind::Zero => "Value is zero",
ErrorKind::NAN => "Value is 'not a number'",
ErrorKind::InvalidInput => "Invalid input",
ErrorKind::InvalidArgumentCount => "Invalid number of arguments",
ErrorKind::DivisionByZero => "Cannot divide by zero",
ErrorKind::NegativeValue => "Value is negative",
ErrorKind::PositiveValue => "Value is positive",
ErrorKind::Empty => "Empty input",
ErrorKind::InvalidExpression => "Invalid expression",
ErrorKind::Unknown => "Unknown error",
}
}
}
impl Eq for Error {}
impl PartialEq for Error {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.kind() == other.kind()
}
}
impl Debug for Detail {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match *self {
Detail::Simple(ref kind) => f.write_str(kind.as_str()),
Detail::Custom(ref custom) => Debug::fmt(custom, f),
}
}
}
impl Error {
/// Creates a new `Error` an `ErrorKind` and inner error.
///
/// # Example
/// ```
/// use prexel::error::{Error, ErrorKind};
///
/// let custom_error = Error::new(ErrorKind::Unknown, "my error");
/// assert_eq!(ErrorKind::Unknown, custom_error.kind());
/// assert_eq!("my error", custom_error.to_string());
/// ```
#[inline]
pub fn new<E>(kind: ErrorKind, error: E) -> Error
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
Error {
detail: Detail::Custom(Box::from(Custom {
kind,
error: error.into(),
})),
}
}
/// Creates an error with the specified message and `ErrorKind::Other`.
///
/// # Example
/// ```
/// use prexel::error::Error;
/// let error = Error::other("custom error");
/// assert_eq!("custom error", error.to_string());
/// ```
#[inline]
pub fn other(msg: &str) -> Error {
Self::new(ErrorKind::Unknown, msg)
}
/// Gets the `ErrorKind` of this error.
///
/// # Example
/// ```
/// use prexel::error::{Error, ErrorKind};
/// let error = Error::from(ErrorKind::InvalidInput);
/// assert_eq!(ErrorKind::InvalidInput, error.kind());
/// ```
#[inline]
pub fn kind(&self) -> ErrorKind {
match self.detail {
Detail::Simple(ref kind) => *kind,
Detail::Custom(ref custom) => custom.kind,
}
}
///Consumes the `Error`, returning its inner error (if any).
///
/// # Example
///```
/// use prexel::error::Error;
/// use prexel::error::ErrorKind;
///
/// fn print_error(error: Error){
/// if let Some(inner_error) = error.into_inner(){
/// println!("Inner error: {}", inner_error)
/// }
/// else{
/// println!("No inner error");
/// }
/// }
///
/// fn main(){
/// // No inner error
/// print_error(Error::from(ErrorKind::InvalidInput));
/// // With inner error
/// print_error(Error::new(ErrorKind::Unknown, "custom error"))
/// }
/// ```
#[inline]
pub fn into_inner(self) -> Option<Box<dyn std::error::Error + Send + Sync>> {
match self.detail {
Detail::Simple(_) => None,
Detail::Custom(custom) => Some(custom.error),
}
}
/// Gets a reference to the inner error (if any).
///
/// # Example
/// ```
/// use prexel::error::{Error, ErrorKind};
/// let error = Error::new(ErrorKind::Overflow, "value has overflow");
/// let inner_error = error.get_ref().unwrap();
/// ```
#[inline]
#[allow(clippy::borrowed_box)]
pub fn get_ref(&self) -> Option<&Box<dyn std::error::Error + Send + Sync>> {
match self.detail {
Detail::Simple(_) => None,
Detail::Custom(ref custom) => Some(&custom.error),
}
}
/// Gets a mutable reference to the inner error (if any).
///
/// # Example
/// ```
/// use prexel::error::{Error, ErrorKind};
/// let mut error = Error::new(ErrorKind::Overflow, "value has overflow");
/// let inner_error = error.get_mut().unwrap();
/// ```
#[inline]
pub fn get_mut(&mut self) -> Option<&mut Box<dyn std::error::Error + Send + Sync + 'static>> {
match self.detail {
Detail::Simple(_) => None,
Detail::Custom(ref mut custom) => Some(&mut custom.error),
}
}
}
impl From<ErrorKind> for Error {
#[inline]
fn from(kind: ErrorKind) -> Self {
Error {
detail: Detail::Simple(kind),
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.detail {
Detail::Simple(ref kind) => f.write_str(kind.as_str()),
Detail::Custom(ref custom) => Display::fmt(custom.error.as_ref(), f),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self.detail {
Detail::Simple(_) => None,
Detail::Custom(ref custom) => custom.error.source(),
}
}
#[allow(deprecated)]
fn cause(&self) -> Option<&dyn std::error::Error> {
match self.detail {
Detail::Simple(_) => None,
Detail::Custom(ref custom) => custom.error.cause(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn custom_error_test() {
let error = Error::new(ErrorKind::Unknown, "Just a test");
if let Detail::Custom(e) = error.detail {
assert_eq!(ErrorKind::Unknown, e.kind);
assert_eq!("Just a test", e.error.to_string())
} else {
unreachable!()
}
}
}