]> Untitled Git - lemmy.git/blob - crates/utils/src/lib.rs
Merge pull request #1938 from LemmyNet/once_cell
[lemmy.git] / crates / utils / src / lib.rs
1 #[macro_use]
2 extern crate strum_macros;
3 #[macro_use]
4 extern crate smart_default;
5
6 pub mod apub;
7 pub mod email;
8 pub mod rate_limit;
9 pub mod request;
10 pub mod settings;
11
12 pub mod claims;
13 #[cfg(test)]
14 mod test;
15 pub mod utils;
16 pub mod version;
17
18 use http::StatusCode;
19 use log::warn;
20 use std::{fmt, fmt::Display};
21 use thiserror::Error;
22
23 pub type ConnectionId = usize;
24
25 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
26 pub struct IpAddr(pub String);
27
28 impl fmt::Display for IpAddr {
29   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30     write!(f, "{}", self.0)
31   }
32 }
33
34 #[macro_export]
35 macro_rules! location_info {
36   () => {
37     format!(
38       "None value at {}:{}, column {}",
39       file!(),
40       line!(),
41       column!()
42     )
43   };
44 }
45
46 #[derive(Debug, Error)]
47 #[error("{{\"error\":\"{message}\"}}")]
48 pub struct ApiError {
49   message: String,
50 }
51
52 impl ApiError {
53   pub fn err_plain(msg: &str) -> Self {
54     ApiError {
55       message: msg.to_string(),
56     }
57   }
58   pub fn err<E: Display>(msg: &str, original_error: E) -> Self {
59     warn!("{}", original_error);
60     ApiError {
61       message: msg.to_string(),
62     }
63   }
64 }
65
66 #[derive(Debug)]
67 pub struct LemmyError {
68   pub inner: anyhow::Error,
69 }
70
71 impl<T> From<T> for LemmyError
72 where
73   T: Into<anyhow::Error>,
74 {
75   fn from(t: T) -> Self {
76     LemmyError { inner: t.into() }
77   }
78 }
79
80 impl Display for LemmyError {
81   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
82     self.inner.fmt(f)
83   }
84 }
85
86 impl actix_web::error::ResponseError for LemmyError {
87   fn status_code(&self) -> StatusCode {
88     match self.inner.downcast_ref::<diesel::result::Error>() {
89       Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
90       _ => StatusCode::INTERNAL_SERVER_ERROR,
91     }
92   }
93 }