blob: 5f35da253d3fbf1d4890f0c01433f6a20b0b6ffc (
plain)
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
|
use std::fmt::Display;
use hyper::StatusCode;
/// Encapsulates a status code and an error message.
///
/// All client errors in [`crate::request`] implement [`Into<Error>`].
#[derive(Debug)]
pub struct Error {
pub code: StatusCode,
pub message: String,
}
impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "error: {}", self.message)
}
}
impl std::error::Error for Error {
}
impl Error {
/// Returns an HTTP response builder with the status code set to `self.code`.
pub fn response_builder(&self) -> hyper::http::response::Builder {
hyper::Response::builder().status(self.code)
}
// some conventient constructors for common errors
pub fn bad_request(message: String) -> Self {
Error{code: StatusCode::BAD_REQUEST, message}
}
pub fn not_found(message: String) -> Self {
Error{code: StatusCode::NOT_FOUND, message}
}
pub fn unauthorized(message: String) -> Self {
Error{code: StatusCode::UNAUTHORIZED, message}
}
pub fn internal(message: String) -> Self {
Error{code: StatusCode::INTERNAL_SERVER_ERROR, message}
}
pub fn method_not_allowed(message: String) -> Self {
Error{code: StatusCode::METHOD_NOT_ALLOWED, message}
}
}
macro_rules! impl_into_http_error {
($type:ident, $status:expr) => {
impl From<$type> for crate::error::Error {
fn from(err: $type) -> Self {
Self{code: $status, message: format!("{}", err)}
}
}
};
}
|