5 use tracing_error::SpanTrace;
7 #[derive(serde::Serialize)]
12 pub struct LemmyError {
13 pub message: Option<String>,
14 pub inner: anyhow::Error,
15 pub context: SpanTrace,
19 /// Create LemmyError from a message, including stack trace
20 pub fn from_message(message: &str) -> Self {
21 let inner = anyhow::anyhow!("{}", message);
23 message: Some(message.into()),
25 context: SpanTrace::capture(),
29 /// Create a LemmyError from error and message, including stack trace
30 pub fn from_error_message<E>(error: E, message: &str) -> Self
32 E: Into<anyhow::Error>,
35 message: Some(message.into()),
37 context: SpanTrace::capture(),
41 /// Add message to existing LemmyError (or overwrite existing error)
42 pub fn with_message(self, message: &str) -> Self {
44 message: Some(message.into()),
49 pub fn to_json(&self) -> Result<String, Self> {
50 let api_error = match &self.message {
51 Some(error) => ApiError {
55 error: "Unknown".into(),
59 Ok(serde_json::to_string(&api_error)?)
63 impl<T> From<T> for LemmyError
65 T: Into<anyhow::Error>,
67 fn from(t: T) -> Self {
71 context: SpanTrace::capture(),
76 impl Debug for LemmyError {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 f.debug_struct("LemmyError")
79 .field("message", &self.message)
80 .field("inner", &self.inner)
81 .field("context", &"SpanTrace")
86 impl Display for LemmyError {
87 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88 if let Some(message) = &self.message {
89 write!(f, "{}: ", message)?;
91 writeln!(f, "{}", self.inner)?;
92 fmt::Display::fmt(&self.context, f)
96 impl actix_web::error::ResponseError for LemmyError {
97 fn status_code(&self) -> http::StatusCode {
98 match self.inner.downcast_ref::<diesel::result::Error>() {
99 Some(diesel::result::Error::NotFound) => http::StatusCode::NOT_FOUND,
100 _ => http::StatusCode::BAD_REQUEST,
104 fn error_response(&self) -> actix_web::HttpResponse {
105 if let Some(message) = &self.message {
106 actix_web::HttpResponse::build(self.status_code()).json(ApiError {
107 error: message.into(),
110 actix_web::HttpResponse::build(self.status_code())
111 .content_type("text/plain")
112 .body(self.inner.to_string())