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
use self::KindPriv::*;
use std::error;
use std::fmt;
pub struct Error {
kind: ErrorKind,
}
pub struct ErrorKind {
kind: KindPriv,
}
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
enum KindPriv {
BadRequest,
NotFound,
Internal,
}
impl Error {
pub fn kind(&self) -> &ErrorKind {
&self.kind
}
}
impl error::Error for Error {
fn description(&self) -> &str {
match self.kind.kind {
BadRequest => "Bad request",
NotFound => "Not found",
Internal => "Internal error",
}
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
kind,
}
}
}
impl fmt::Debug for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Error")
.field("kind", &self.kind)
.finish()
}
}
impl fmt::Display for Error {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
use std::error::Error;
if let Some(cause) = self.cause() {
write!(fmt, "{}: {}", self.description(), cause)
} else {
fmt.write_str(self.description())
}
}
}
impl ErrorKind {
pub fn bad_request() -> ErrorKind {
ErrorKind { kind: BadRequest }
}
pub fn is_bad_request(&self) -> bool {
self.kind == BadRequest
}
pub fn not_found() -> ErrorKind {
ErrorKind { kind: NotFound }
}
pub fn is_not_found(&self) -> bool {
self.kind == NotFound
}
pub fn internal() -> ErrorKind {
ErrorKind { kind: Internal }
}
pub fn is_internal(&self) -> bool {
self.kind == Internal
}
}
impl fmt::Debug for ErrorKind {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match self.kind {
BadRequest => "ErrorKind::BadRequest",
NotFound => "ErrorKind::NotFound",
Internal => "ErrorKind::Internal",
}.fmt(fmt)
}
}