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)),
}
}
}