1#[cfg(test)]
2mod tests;
3
4pub mod problem;
5pub mod page;
6pub use problem::problem;
7
8use crate::header::Header;
9use crate::request::Request;
10use crate::response::{Response, StatusCodeReasonPhrase, STATUS_CODE_REASON_PHRASE};
11
12pub trait IntoResponse {
20 fn into_response(self) -> Response;
21}
22
23impl IntoResponse for Response {
24 fn into_response(self) -> Response {
25 self
26 }
27}
28
29impl<T: IntoResponse, E: IntoResponse> IntoResponse for Result<T, E> {
32 fn into_response(self) -> Response {
33 match self {
34 Ok(value) => value.into_response(),
35 Err(error) => error.into_response(),
36 }
37 }
38}
39
40impl IntoResponse for String {
42 fn into_response(self) -> Response {
43 Response::text(STATUS_CODE_REASON_PHRASE.n200_ok, &self)
44 }
45}
46
47impl IntoResponse for &'static str {
49 fn into_response(self) -> Response {
50 Response::text(STATUS_CODE_REASON_PHRASE.n200_ok, self)
51 }
52}
53
54impl<T: IntoResponse> IntoResponse for (&'static StatusCodeReasonPhrase, T) {
57 fn into_response(self) -> Response {
58 let (status, inner) = self;
59 let mut response = inner.into_response();
60 response.status_code = *status.status_code;
61 response.reason_phrase = status.reason_phrase.to_string();
62 response
63 }
64}
65
66#[derive(Debug, PartialEq, Eq)]
87pub enum AppError {
88 BadRequest(String),
90 Unauthorized,
92 Forbidden,
94 NotFound(String),
96 Conflict(String),
98 UnprocessableEntity(String),
100 TooManyRequests,
102 PayloadTooLarge(String),
104 Internal(String),
106}
107
108impl IntoResponse for AppError {
109 fn into_response(self) -> Response {
110 let (status, body_str) = match &self {
111 AppError::BadRequest(msg) => (STATUS_CODE_REASON_PHRASE.n400_bad_request, msg.as_str()),
112 AppError::Unauthorized => (STATUS_CODE_REASON_PHRASE.n401_unauthorized, "Unauthorized"),
113 AppError::Forbidden => (STATUS_CODE_REASON_PHRASE.n403_forbidden, "Forbidden"),
114 AppError::NotFound(msg) => (STATUS_CODE_REASON_PHRASE.n404_not_found, msg.as_str()),
115 AppError::Conflict(msg) => (STATUS_CODE_REASON_PHRASE.n409_conflict, msg.as_str()),
116 AppError::UnprocessableEntity(msg) => (STATUS_CODE_REASON_PHRASE.n422_unprocessable_entity, msg.as_str()),
117 AppError::TooManyRequests => (STATUS_CODE_REASON_PHRASE.n429_too_many_requests, "Too Many Requests"),
118 AppError::PayloadTooLarge(msg) => (STATUS_CODE_REASON_PHRASE.n413_payload_too_large, msg.as_str()),
119 AppError::Internal(msg) => (STATUS_CODE_REASON_PHRASE.n500_internal_server_error, msg.as_str()),
120 };
121
122 let detail = match &self {
125 AppError::Unauthorized | AppError::Forbidden | AppError::TooManyRequests => "",
126 _ => body_str,
127 };
128 let dummy = Request {
129 method: "GET".to_string(),
130 request_uri: "/".to_string(),
131 http_version: "HTTP/1.1".to_string(),
132 headers: vec![],
133 body: Default::default(),
134 };
135 problem::with_headers(status, detail, body_str, Some(Header::get_header_list(&dummy)))
136 }
137}