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
mod any_http_error;
pub mod option_ext;
mod reason;
pub mod result_ext;

use std::error::Error;
use std::fmt;

pub use any_http_error::AnyHttpError;
pub use http::StatusCode;
use http::{HeaderName, HeaderValue};
pub use option_ext::OptionExt;
pub use reason::Reason;
pub use result_ext::ResultExt;

pub trait HttpError: Error {
    fn status_code(&self) -> StatusCode;

    fn reason(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(reason) = self.status_code().canonical_reason() {
            f.write_str(reason)?;
        }
        Ok(())
    }

    fn headers(&self) -> Option<Vec<(HeaderName, HeaderValue)>> {
        None
    }
}

impl<E> HttpError for Box<E>
where
    E: HttpError,
{
    fn status_code(&self) -> StatusCode {
        HttpError::status_code(&**self)
    }

    fn reason(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        HttpError::reason(&**self, f)
    }

    fn headers(&self) -> Option<Vec<(HeaderName, HeaderValue)>> {
        HttpError::headers(&**self)
    }
}

impl<E> From<E> for Box<dyn HttpError>
where
    E: HttpError + 'static,
{
    fn from(err: E) -> Self {
        Box::new(err)
    }
}