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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
//! This crate make a series of enhancements for [Axum](axum)
//!
use axum::{http::StatusCode, response::IntoResponse, response::Response};
use std::fmt::{Debug, Display};

pub mod filter;

/// The error type contains a [status code](StatusCode) and a string message.
///
/// It implements [IntoResponse], so can be used in [axum] handler.
///
/// # Example
/// 
/// ```
/// # use axum::response::IntoResponse;
/// # use axum_help::HttpError;
/// #
/// fn handler() -> Result<impl IntoResponse, HttpError> {
///     Ok(())
/// }
/// ```
/// Often it can to more convenient to use [HttpResult]
///
/// # Example
/// ```
/// # use axum::response::IntoResponse;
/// # use axum_help::HttpResult;
/// #
/// fn handler() -> HttpResult<impl IntoResponse> {
///     Ok(())
/// }
/// ```
#[derive(PartialEq, Debug)]
pub struct HttpError {
    pub message: String,
    pub status_code: StatusCode,
}

impl IntoResponse for HttpError {
    fn into_response(self) -> Response {
        let mut response = self.message.into_response();
        *response.status_mut() = self.status_code;
        response
    }
}

impl<E> From<E> for HttpError
where
    E: Debug + Display + Sync + Send + 'static,
{
    fn from(e: E) -> Self {
        Self {
            message: format!("{:?}", e),
            status_code: StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

/// Construct an ad-hoc error from a string or existing error value.
///
/// This evaluates to an [HttpError]. It can take either just a string, or
/// a format string with arguments. It also can take any custom type
/// which implements Debug and Display.
///
/// If status code is not specified, [INTERNAL_SERVER_ERROR](StatusCode::INTERNAL_SERVER_ERROR)
/// will be used.
#[macro_export]
macro_rules! http_err {
    ($status: path, $fmt: literal, $($args: tt)+) => {
        HttpError {
            message: format!($fmt, $($args)+),
            status_code: $status
        }
    };
    ($status: path, $msg: literal) => {
        HttpError {
            message: $msg.to_string(),
            status_code: $status
        }
    };
    ($fmt: literal, $($args: tt)+) => {
        http_err!(StatusCode::INTERNAL_SERVER_ERROR, $fmt, $($args)+)
    };
    ($msg: literal) => {
        http_err!(StatusCode::INTERNAL_SERVER_ERROR, $msg)
    };
}

/// Return early with an [`HttpError`]
///
/// This macro is equivalent to `return Err(`[`http_err!($args...)`][http_err!]`)`.
///
/// The surrounding function's or closure's return value is required to be
/// Result<_, [`HttpError`]>
///
/// If status code is not specified, [INTERNAL_SERVER_ERROR](StatusCode::INTERNAL_SERVER_ERROR)
/// will be used.
///
/// # Example
///
/// ```
/// # use http::StatusCode;
/// # use axum_help::{http_bail, HttpError, http_err, HttpResult};
/// # use axum::response::IntoResponse;
/// #
/// fn get() -> HttpResult<()> {
///     http_bail!(StatusCode::BAD_REQUEST, "Bad Request: {}", "some reason");
/// }
/// ```
#[macro_export]
macro_rules! http_bail {
    ($($args: tt)+) => {
        return Err(http_err!($($args)+));
    };
}

/// Easily convert [std::result::Result] to [HttpResult]
///
/// # Example
/// ```
/// # use std::io::{Error, ErrorKind};
/// # use axum_help::{HttpResult, HttpContext};
/// # use http::StatusCode;
/// #
/// fn handler() -> HttpResult<()> {
/// #   let result = Err(Error::new(ErrorKind::InvalidInput, "bad input"));
///     result.http_context(StatusCode::BAD_REQUEST, "bad request")?;   
/// #   let result = Err(Error::new(ErrorKind::InvalidInput, "bad input"));
///     result.http_error("bad request")?;
/// 
///     Ok(())
/// }
/// ```
pub trait HttpContext<T> {
    fn http_context<C>(self, status_code: StatusCode, extra_msg: C) -> Result<T, HttpError>
    where
        C: Display + Send + Sync + 'static;

    fn http_error<C>(self, extra_msg: C) -> Result<T, HttpError>
    where
        C: Display + Send + Sync + 'static;
}

impl<T, E> HttpContext<T> for Result<T, E>
where
    E: Debug + Sync + Send + 'static,
{
    fn http_context<C>(self, status_code: StatusCode, extra_msg: C) -> Result<T, HttpError>
    where
        C: Display + Send + Sync + 'static,
    {
        self.map_err(|e| HttpError {
            message: format!("{}: {:?}", extra_msg, e),
            status_code,
        })
    }

    fn http_error<C>(self, extra_msg: C) -> Result<T, HttpError>
    where
        C: Display + Send + Sync + 'static,
    {
        self.map_err(|e| HttpError {
            message: format!("{}: {:?}", extra_msg, e),
            status_code: StatusCode::INTERNAL_SERVER_ERROR,
        })
    }
}

/// convenient return type when writing [axum] handler.
/// 
pub type HttpResult<T> = Result<T, HttpError>;

#[cfg(test)]
mod test {
    use super::HttpError;
    use axum::http::StatusCode;

    #[test]
    fn test_macros() -> Result<(), HttpError> {
        let error = HttpError {
            message: "aaa".to_string(),
            status_code: StatusCode::INTERNAL_SERVER_ERROR,
        };
        assert_eq!(error, http_err!(StatusCode::INTERNAL_SERVER_ERROR, "aaa"));
        assert_eq!(
            error,
            http_err!(StatusCode::INTERNAL_SERVER_ERROR, "{}aa", "a")
        );
        assert_eq!(error, http_err!("aaa"));
        assert_eq!(error, http_err!("{}aa", "a"));
        Ok(())
    }
}