json_response/
failed_resp.rs

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