routerify_json_response/failed_resp.rs
1use crate::gen_resp::gen_response;
2use http::{Response, StatusCode};
3use http_body::Body as HttpBody;
4use serde::Serialize;
5
6const STATUS_FAILED: &'static str = "failed";
7
8#[derive(Serialize, Debug, Clone)]
9#[serde(rename_all = "camelCase")]
10struct FailedResp {
11 status: &'static str,
12 code: u16,
13 message: String,
14}
15
16/// Generates a failed JSON response with the provided message and status code.
17///
18/// It generates JSON response in the following JSON format:
19///
20/// ```json
21/// {
22/// "status": "failed",
23/// "code": "<status_code>",
24/// "message": "<error_message>"
25/// }
26///```
27///
28/// # Examples
29///
30/// ```
31/// use hyper::{Body, Request, Response, StatusCode};
32/// use routerify_json_response::{json_failed_resp_with_message};
33///
34/// async fn list_books_handler(_: Request<Body>) -> Result<Response<Body>, routerify_json_response::Error> {
35/// // Generate a failed JSON response in the following format:
36/// // { "status": "failed", code: 500, data: "Internal Server Error: Couldn't fetch book list from database" }
37/// json_failed_resp_with_message(
38/// StatusCode::INTERNAL_SERVER_ERROR,
39/// "Couldn't fetch book list from database",
40/// )
41/// }
42/// ```
43pub fn json_failed_resp_with_message<B, M>(code: StatusCode, message: M) -> crate::Result<Response<B>>
44where
45 B: HttpBody + From<Vec<u8>> + Send + Sync + Unpin + 'static,
46 M: Into<String>,
47{
48 let resp_data = FailedResp {
49 status: STATUS_FAILED,
50 code: code.as_u16(),
51 message: format!("{}: {}", code.canonical_reason().unwrap(), message.into()),
52 };
53
54 gen_response(code, &resp_data)
55}
56
57/// Generates a failed JSON response with the status code specific message and status code.
58///
59/// It generates JSON response in the following JSON format:
60///
61/// ```json
62/// {
63/// "status": "failed",
64/// "code": "<status_code>",
65/// "message": "<status_code_message>"
66/// }
67///```
68///
69/// # Examples
70///
71/// ```
72/// use hyper::{Body, Request, Response, StatusCode};
73/// use routerify_json_response::{json_failed_resp};
74///
75/// async fn list_books_handler(_: Request<Body>) -> Result<Response<Body>, routerify_json_response::Error> {
76/// // Generate a failed JSON response in the following format:
77/// // { "status": "failed", code: 500, data: "Internal Server Error" }
78/// json_failed_resp(StatusCode::INTERNAL_SERVER_ERROR)
79/// }
80/// ```
81pub fn json_failed_resp<B>(code: StatusCode) -> crate::Result<Response<B>>
82where
83 B: HttpBody + From<Vec<u8>> + Send + Sync + Unpin + 'static,
84{
85 let resp_data = FailedResp {
86 status: STATUS_FAILED,
87 code: code.as_u16(),
88 message: code.canonical_reason().unwrap().to_string(),
89 };
90
91 gen_response(code, &resp_data)
92}