]> Untitled Git - lemmy.git/blob - crates/utils/src/error.rs
don't strip, log trace if requested (#3425)
[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     // print anyhow including trace
94     // https://docs.rs/anyhow/latest/anyhow/struct.Error.html#display-representations
95     // this will print the anyhow trace (only if it exists)
96     // and if RUST_BACKTRACE=1, also a full backtrace
97     writeln!(f, "{:?}", self.inner)?;
98     fmt::Display::fmt(&self.context, f)
99   }
100 }
101
102 impl actix_web::error::ResponseError for LemmyError {
103   fn status_code(&self) -> http::StatusCode {
104     match self.inner.downcast_ref::<diesel::result::Error>() {
105       Some(diesel::result::Error::NotFound) => http::StatusCode::NOT_FOUND,
106       _ => http::StatusCode::BAD_REQUEST,
107     }
108   }
109
110   fn error_response(&self) -> actix_web::HttpResponse {
111     if let Some(message) = &self.message {
112       actix_web::HttpResponse::build(self.status_code()).json(ApiError {
113         error: message.into(),
114       })
115     } else {
116       actix_web::HttpResponse::build(self.status_code())
117         .content_type("text/plain")
118         .body(self.inner.to_string())
119     }
120   }
121 }