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
use core::{convert::Infallible, fmt};

use std::error;

use std::backtrace::Backtrace;

use crate::{
    body::ResponseBody,
    http::{StatusCode, WebResponse},
    service::Service,
    WebContext,
};

use super::Error;

/// error type derive from http status code. produce minimal "StatusCode Reason" response and stack backtrace
/// of the location status code error occurs.
pub struct ErrorStatus {
    status: StatusCode,
    _back_trace: Backtrace,
}

impl ErrorStatus {
    /// construct an ErrorStatus type from [`StatusCode::INTERNAL_SERVER_ERROR`]
    pub fn internal() -> Self {
        // verbosity of constructor is desired here so back trace capture
        // can direct capture the call site.
        Self {
            status: StatusCode::BAD_REQUEST,
            _back_trace: Backtrace::capture(),
        }
    }

    /// construct an ErrorStatus type from [`StatusCode::BAD_REQUEST`]
    pub fn bad_request() -> Self {
        Self {
            status: StatusCode::BAD_REQUEST,
            _back_trace: Backtrace::capture(),
        }
    }
}

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

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

impl error::Error for ErrorStatus {
    #[cfg(feature = "nightly")]
    fn provide<'a>(&'a self, request: &mut error::Request<'a>) {
        request.provide_ref(&self._back_trace);
    }
}

impl From<StatusCode> for ErrorStatus {
    fn from(status: StatusCode) -> Self {
        Self {
            status,
            _back_trace: Backtrace::capture(),
        }
    }
}

impl<C> From<StatusCode> for Error<C> {
    fn from(e: StatusCode) -> Self {
        Error::from(ErrorStatus::from(e))
    }
}

impl<C> From<ErrorStatus> for Error<C> {
    fn from(e: ErrorStatus) -> Self {
        Error::from_service(e)
    }
}

impl<'r, C, B> Service<WebContext<'r, C, B>> for ErrorStatus {
    type Response = WebResponse;
    type Error = Infallible;

    async fn call(&self, ctx: WebContext<'r, C, B>) -> Result<Self::Response, Self::Error> {
        self.status.call(ctx).await
    }
}

impl<'r, C, B> Service<WebContext<'r, C, B>> for StatusCode {
    type Response = WebResponse;
    type Error = Infallible;

    async fn call(&self, ctx: WebContext<'r, C, B>) -> Result<Self::Response, Self::Error> {
        let mut res = ctx.into_response(ResponseBody::empty());
        *res.status_mut() = *self;
        Ok(res)
    }
}