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
use hyper::server::{Request, Response};
use hyper::{Error, StatusCode};
use futures::future;
use super::FutureObject;
use std::io::{self, ErrorKind as IoErrorKind};
use std::fmt;
#[derive(Debug)]
pub enum Exception {
Io(io::Error),
Method,
Typo,
Route,
}
impl Exception {
pub fn not_found() -> Self {
Exception::Io(io::Error::from(IoErrorKind::NotFound))
}
}
impl Into<Exception> for io::Error {
fn into(self) -> Exception {
Exception::Io(self)
}
}
#[derive(Default, Debug, Clone)]
pub struct ExceptionHandler;
pub trait ExceptionHandlerService: fmt::Debug {
fn call<E>(e: E, req: Request) -> Result<Response, Error>
where
E: Into<Exception>;
}
impl ExceptionHandlerService for ExceptionHandler {
fn call<E>(e: E, _req: Request) -> Result<Response, Error>
where
E: Into<Exception>,
{
use Exception::*;
match e.into() {
Io(i) => match i.kind() {
IoErrorKind::NotFound => Ok(Response::new().with_status(StatusCode::NotFound)),
IoErrorKind::PermissionDenied => Ok(Response::new().with_status(StatusCode::Forbidden)),
_ => Ok(Response::new().with_status(StatusCode::InternalServerError)),
},
Method => Ok(Response::new().with_status(StatusCode::MethodNotAllowed)),
Typo | Route => Ok(Response::new().with_status(StatusCode::InternalServerError)),
}
}
}
pub trait ExceptionHandlerServiceAsync: ExceptionHandlerService {
fn call_async<E>(e: E, req: Request) -> FutureObject
where
E: Into<Exception>;
}
impl<T> ExceptionHandlerServiceAsync for T
where
T: ExceptionHandlerService,
{
fn call_async<E>(e: E, req: Request) -> FutureObject
where
E: Into<Exception>,
{
match Self::call(e, req) {
Ok(res) => Box::new(future::ok(res)),
Err(e) => Box::new(future::err(e)),
}
}
}