]> Untitled Git - lemmy.git/blob - crates/utils/src/error.rs
Set attribute `deny_unknown_fields` for Lemmy config (#2852)
[lemmy.git] / crates / utils / src / error.rs
1 use std::{
2   fmt,
3   fmt::{Debug, Display},
4 };
5 use tracing_error::SpanTrace;
6
7 #[derive(serde::Serialize)]
8 struct ApiError {
9   error: String,
10 }
11
12 pub type LemmyResult<T> = Result<T, LemmyError>;
13
14 pub struct LemmyError {
15   pub message: Option<String>,
16   pub inner: anyhow::Error,
17   pub context: SpanTrace,
18 }
19
20 impl LemmyError {
21   /// Create LemmyError from a message, including stack trace
22   pub fn from_message(message: &str) -> Self {
23     let inner = anyhow::anyhow!("{}", message);
24     LemmyError {
25       message: Some(message.into()),
26       inner,
27       context: SpanTrace::capture(),
28     }
29   }
30
31   /// Create a LemmyError from error and message, including stack trace
32   pub fn from_error_message<E>(error: E, message: &str) -> Self
33   where
34     E: Into<anyhow::Error>,
35   {
36     LemmyError {
37       message: Some(message.into()),
38       inner: error.into(),
39       context: SpanTrace::capture(),
40     }
41   }
42
43   /// Add message to existing LemmyError (or overwrite existing error)
44   pub fn with_message(self, message: &str) -> Self {
45     LemmyError {
46       message: Some(message.into()),
47       ..self
48     }
49   }
50
51   pub fn to_json(&self) -> Result<String, Self> {
52     let api_error = match &self.message {
53       Some(error) => ApiError {
54         error: error.into(),
55       },
56       None => ApiError {
57         error: "Unknown".into(),
58       },
59     };
60
61     Ok(serde_json::to_string(&api_error)?)
62   }
63 }
64
65 impl<T> From<T> for LemmyError
66 where
67   T: Into<anyhow::Error>,
68 {
69   fn from(t: T) -> Self {
70     LemmyError {
71       message: None,
72       inner: t.into(),
73       context: SpanTrace::capture(),
74     }
75   }
76 }
77
78 impl Debug for LemmyError {
79   fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80     f.debug_struct("LemmyError")
81       .field("message", &self.message)
82       .field("inner", &self.inner)
83       .field("context", &self.context)
84       .finish()
85   }
86 }
87
88 impl Display for LemmyError {
89   fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90     if let Some(message) = &self.message {
91       write!(f, "{message}: ")?;
92     }
93     writeln!(f, "{}", self.inner)?;
94     fmt::Display::fmt(&self.context, f)
95   }
96 }
97
98 impl actix_web::error::ResponseError for LemmyError {
99   fn status_code(&self) -> http::StatusCode {
100     match self.inner.downcast_ref::<diesel::result::Error>() {
101       Some(diesel::result::Error::NotFound) => http::StatusCode::NOT_FOUND,
102       _ => http::StatusCode::BAD_REQUEST,
103     }
104   }
105
106   fn error_response(&self) -> actix_web::HttpResponse {
107     if let Some(message) = &self.message {
108       actix_web::HttpResponse::build(self.status_code()).json(ApiError {
109         error: message.into(),
110       })
111     } else {
112       actix_web::HttpResponse::build(self.status_code())
113         .content_type("text/plain")
114         .body(self.inner.to_string())
115     }
116   }
117 }