]> Untitled Git - lemmy.git/blob - crates/utils/src/lib.rs
5eaff30e80b914e71808e884870a83e9b71b9288
[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 std::{fmt, fmt::Display};
20 use thiserror::Error;
21 use tracing::warn;
22 use tracing_error::SpanTrace;
23
24 pub type ConnectionId = usize;
25
26 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
27 pub struct IpAddr(pub String);
28
29 impl fmt::Display for IpAddr {
30   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31     write!(f, "{}", self.0)
32   }
33 }
34
35 #[macro_export]
36 macro_rules! location_info {
37   () => {
38     format!(
39       "None value at {}:{}, column {}",
40       file!(),
41       line!(),
42       column!()
43     )
44   };
45 }
46
47 #[derive(Debug, Error)]
48 #[error("{{\"error\":\"{message}\"}}")]
49 pub struct ApiError {
50   message: String,
51 }
52
53 impl ApiError {
54   pub fn err_plain(msg: &str) -> Self {
55     ApiError {
56       message: msg.to_string(),
57     }
58   }
59   pub fn err<E: Display>(msg: &str, original_error: E) -> Self {
60     warn!("{}", original_error);
61     ApiError {
62       message: msg.to_string(),
63     }
64   }
65 }
66
67 #[derive(Debug)]
68 pub struct LemmyError {
69   pub inner: anyhow::Error,
70   pub context: SpanTrace,
71 }
72
73 impl<T> From<T> for LemmyError
74 where
75   T: Into<anyhow::Error>,
76 {
77   fn from(t: T) -> Self {
78     LemmyError {
79       inner: t.into(),
80       context: SpanTrace::capture(),
81     }
82   }
83 }
84
85 impl Display for LemmyError {
86   fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
87     self.inner.fmt(f)?;
88     self.context.fmt(f)
89   }
90 }
91
92 impl actix_web::error::ResponseError for LemmyError {
93   fn status_code(&self) -> StatusCode {
94     match self.inner.downcast_ref::<diesel::result::Error>() {
95       Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
96       _ => StatusCode::INTERNAL_SERVER_ERROR,
97     }
98   }
99 }