foxtive/enums/
app_message.rs

1#[cfg(feature = "reqwest")]
2use crate::helpers::reqwest::ReqwestResponseError;
3use crate::results::AppResult;
4use http::StatusCode;
5use std::error::Error;
6use std::fmt::{Debug, Display, Formatter};
7use thiserror::Error;
8
9#[derive(Error, Debug)]
10pub enum AppMessage {
11    Unauthorized,
12    Forbidden,
13    InternalServerError,
14    ErrorMessage(String, StatusCode),
15    InternalServerErrorMessage(&'static str),
16    Redirect(&'static str),
17    SuccessMessage(&'static str),
18    SuccessMessageString(String),
19    WarningMessage(&'static str),
20    WarningMessageString(String),
21    UnAuthorizedMessage(&'static str),
22    UnAuthorizedMessageString(String),
23    ForbiddenMessage(&'static str),
24    ForbiddenMessageString(String),
25    EntityNotFound(String),
26    #[cfg(feature = "reqwest")]
27    ReqwestResponseError(ReqwestResponseError),
28}
29
30fn get_status_code(status: &AppMessage) -> StatusCode {
31    match status {
32        AppMessage::SuccessMessage(_) | AppMessage::SuccessMessageString(_) => StatusCode::OK,
33        AppMessage::WarningMessage(_) | AppMessage::WarningMessageString(_) => {
34            StatusCode::BAD_REQUEST
35        }
36        AppMessage::ErrorMessage(_, status) => *status,
37        AppMessage::Unauthorized
38        | AppMessage::UnAuthorizedMessage(_)
39        | AppMessage::UnAuthorizedMessageString(_) => StatusCode::UNAUTHORIZED,
40        AppMessage::Forbidden
41        | AppMessage::ForbiddenMessage(_)
42        | AppMessage::ForbiddenMessageString(_) => StatusCode::FORBIDDEN,
43        _ => StatusCode::INTERNAL_SERVER_ERROR, // all database-related errors are 500
44    }
45}
46
47impl Display for AppMessage {
48    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49        write!(f, "{}", self.message())
50    }
51}
52
53impl AppMessage {
54    /// Get the status code
55    pub fn status_code(&self) -> StatusCode {
56        get_status_code(self)
57    }
58
59    /// Get the message
60    pub fn message(&self) -> String {
61        #[allow(deprecated)]
62        self.description().to_string()
63    }
64
65    /// Convert to anyhow::Error
66    pub fn ae(self) -> anyhow::Error {
67        self.into_anyhow()
68    }
69
70    /// Convert to AppResult
71    pub fn ar<T>(self) -> AppResult<T> {
72        self.into_result::<T>()
73    }
74
75    /// Convert to anyhow::Error
76    pub fn into_anyhow(self) -> anyhow::Error {
77        anyhow::Error::from(self)
78    }
79
80    /// Convert to AppResult
81    pub fn into_result<T>(self) -> AppResult<T> {
82        Err(anyhow::Error::from(self))
83    }
84}
85
86impl From<crate::Error> for AppMessage {
87    fn from(value: anyhow::Error) -> Self {
88        value.downcast::<AppMessage>().unwrap_or_else(|e| {
89            AppMessage::ErrorMessage(e.to_string(), StatusCode::INTERNAL_SERVER_ERROR)
90        })
91    }
92}