rust_web_server/error/
mod.rs1#[cfg(test)]
2mod tests;
3
4use crate::header::Header;
5use crate::mime_type::MimeType;
6use crate::range::Range;
7use crate::request::Request;
8use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
9
10pub trait IntoResponse {
18 fn into_response(self) -> Response;
19}
20
21impl IntoResponse for Response {
22 fn into_response(self) -> Response {
23 self
24 }
25}
26
27#[derive(Debug, PartialEq, Eq)]
47pub enum AppError {
48 BadRequest(String),
50 Unauthorized,
52 Forbidden,
54 NotFound(String),
56 Conflict(String),
58 UnprocessableEntity(String),
60 Internal(String),
62}
63
64impl IntoResponse for AppError {
65 fn into_response(self) -> Response {
66 let (status, body_str) = match &self {
67 AppError::BadRequest(msg) => (STATUS_CODE_REASON_PHRASE.n400_bad_request, msg.as_str()),
68 AppError::Unauthorized => (STATUS_CODE_REASON_PHRASE.n401_unauthorized, "Unauthorized"),
69 AppError::Forbidden => (STATUS_CODE_REASON_PHRASE.n403_forbidden, "Forbidden"),
70 AppError::NotFound(msg) => (STATUS_CODE_REASON_PHRASE.n404_not_found, msg.as_str()),
71 AppError::Conflict(msg) => (STATUS_CODE_REASON_PHRASE.n409_conflict, msg.as_str()),
72 AppError::UnprocessableEntity(msg) => (STATUS_CODE_REASON_PHRASE.n422_unprocessable_entity, msg.as_str()),
73 AppError::Internal(msg) => (STATUS_CODE_REASON_PHRASE.n500_internal_server_error, msg.as_str()),
74 };
75
76 let dummy = Request {
77 method: "GET".to_string(),
78 request_uri: "/".to_string(),
79 http_version: "HTTP/1.1".to_string(),
80 headers: vec![],
81 body: vec![],
82 };
83 let header_list = Header::get_header_list(&dummy);
84 let body = body_str.as_bytes().to_vec();
85 let content_range = Range::get_content_range(body, MimeType::TEXT_PLAIN.to_string());
86 Response::get_response(status, Some(header_list), Some(vec![content_range]))
87 }
88}