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