5 use tracing_error::SpanTrace;
7 #[derive(serde::Serialize)]
12 pub type LemmyResult<T> = Result<T, LemmyError>;
14 pub struct LemmyError {
15 pub message: Option<String>,
16 pub inner: anyhow::Error,
17 pub context: SpanTrace,
21 /// Create LemmyError from a message, including stack trace
22 pub fn from_message(message: &str) -> Self {
23 let inner = anyhow::anyhow!("{}", message);
25 message: Some(message.into()),
27 context: SpanTrace::capture(),
31 /// Create a LemmyError from error and message, including stack trace
32 pub fn from_error_message<E>(error: E, message: &str) -> Self
34 E: Into<anyhow::Error>,
37 message: Some(message.into()),
39 context: SpanTrace::capture(),
43 /// Add message to existing LemmyError (or overwrite existing error)
44 pub fn with_message(self, message: &str) -> Self {
46 message: Some(message.into()),
51 pub fn to_json(&self) -> Result<String, Self> {
52 let api_error = match &self.message {
53 Some(error) => ApiError {
57 error: "Unknown".into(),
61 Ok(serde_json::to_string(&api_error)?)
65 impl<T> From<T> for LemmyError
67 T: Into<anyhow::Error>,
69 fn from(t: T) -> Self {
73 context: SpanTrace::capture(),
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", &"SpanTrace")
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}: ")?;
93 writeln!(f, "{}", self.inner)?;
94 fmt::Display::fmt(&self.context, f)
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,
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(),
112 actix_web::HttpResponse::build(self.status_code())
113 .content_type("text/plain")
114 .body(self.inner.to_string())