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
use crate::header::StatusCode;

use std::{fmt, error, io};
use error::Error as ErrorTrait;


pub type Result<T> = std::result::Result<T, Error>;


/// A universal error type which contains a source and a kind.
/// 
/// An error is either associated with the client or the server.
#[derive(Debug)]
pub struct Error {
	kind: ErrorKind,
	source: Option<Box<dyn ErrorTrait + Send + Sync>>
}

impl Error {
	/// Creates a new error.
	pub fn new<K, E>(kind: K, error: E) -> Self
	where
		K: Into<ErrorKind>,
		E: Into<Box<dyn ErrorTrait + Send + Sync>> {
		Self {
			kind: kind.into(),
			source: Some(error.into())
		}
	}

	/// Creates a new error without a source.
	pub fn empty<K>(kind: K) -> Self
	where K: Into<ErrorKind> {
		Self {
			kind: kind.into(),
			source: None
		}
	}

	/// Returns the `StatusCode` corresponding to the `ErrorKind`.
	pub fn status_code(&self) -> StatusCode {
		match self.kind {
			ErrorKind::Client(c) => c.into(),
			ErrorKind::Server(s) => s.into()
		}
	}

	/// Returns a new error from an io::Error originating from the client.
	pub fn from_client_io(error: io::Error) -> Self {
		// try to detect if source is known to us
		Self::new(
			ClientErrorKind::from_io(&error),
			error
		)
	}

	/// Returns a new error originating from the server.
	pub fn from_server_error<E>(error: E) -> Self
	where E: Into<Box<dyn ErrorTrait + Send + Sync>> {
		Self::new(ServerErrorKind::InternalServerError, error)
	}
}

impl<T> From<T> for Error
where T: Into<ErrorKind> {
	fn from(e: T) -> Self {
		Self::empty(e)
	}
}

#[cfg(feature = "json")]
mod deserialize_error {
	use super::*;

	use types::request::DeserializeError;

	impl From<DeserializeError> for Error {
		fn from(e: DeserializeError) -> Self {
			Self::new(ClientErrorKind::BadRequest, e)
		}
	}
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Debug::fmt(self, f)
	}
}

impl error::Error for Error {
	fn source(&self) -> Option<&(dyn error::Error + 'static)> {
		self.source.as_ref().map(|e| e.source()).flatten()
	}
}

/// An error can either come from the client or the server.
#[derive(Debug)]
pub enum ErrorKind {
	Client(ClientErrorKind),
	Server(ServerErrorKind)
}


impl From<ClientErrorKind> for ErrorKind {
	fn from(k: ClientErrorKind) -> Self {
		Self::Client(k)
	}
}

impl From<ServerErrorKind> for ErrorKind {
	fn from(k: ServerErrorKind) -> Self {
		Self::Server(k)
	}
}


macro_rules! error_kind {
	($name:ident, $($kind:ident => $status:ident),*) => (
		#[derive(Debug, Clone, Copy, PartialEq, Eq)]
		pub enum $name {
			$($kind),*
		}

		impl From<$name> for StatusCode {
			fn from(k: $name) -> Self {
				match k {
					$($name::$kind => Self::$status),*
				}
			}
		}
	)
}

// impl ClientErrorKind
error_kind!( ClientErrorKind,
	BadRequest => BAD_REQUEST,
	Unauthorized => UNAUTHORIZED,
	PaymentRequired => PAYMENT_REQUIRED,
	Forbidden => FORBIDDEN,
	NotFound => NOT_FOUND,
	MethodNotAllowed => METHOD_NOT_ALLOWED,
	NotAcceptable => NOT_ACCEPTABLE,
	ProxyAuthenticationRequired => PROXY_AUTHENTICATION_REQUIRED,
	RequestTimeout => REQUEST_TIMEOUT,
	Conflict => CONFLICT,
	Gone => GONE,
	LengthRequired => LENGTH_REQUIRED,
	PreconditionFailed => PRECONDITION_FAILED,
	RequestEntityTooLarge => PAYLOAD_TOO_LARGE,
	RequestURITooLarge => URI_TOO_LONG,
	UnsupportedMediaType => UNSUPPORTED_MEDIA_TYPE,
	RequestedRangeNotSatisfiable => RANGE_NOT_SATISFIABLE,
	ExpectationFailed => EXPECTATION_FAILED
);

impl ClientErrorKind {
	/// Converts an io::Error into the appropriate kind.
	pub fn from_io(error: &io::Error) -> Self {
		use io::ErrorKind::*;
		match error.kind() {
			NotFound => Self::NotFound,
			PermissionDenied => Self::Unauthorized,
			// this should probably not happen?
			AlreadyExists => Self::Conflict,
			UnexpectedEof => Self::RequestEntityTooLarge,
			InvalidInput |
			InvalidData |
			Other => Self::BadRequest,
			TimedOut => Self::RequestTimeout,
			_ => Self::ExpectationFailed
		}
	}
}

// Impl ServerErrorKind
error_kind!( ServerErrorKind,
	InternalServerError => INTERNAL_SERVER_ERROR,
	NotImplemented => NOT_IMPLEMENTED,
	BadGateway => BAD_GATEWAY,
	ServiceUnavailable => SERVICE_UNAVAILABLE,
	GatewayTimeout => GATEWAY_TIMEOUT
);