2 extern crate strum_macros;
4 extern crate smart_default;
20 pub use sensitive::Sensitive;
22 use actix_web::HttpResponse;
24 use std::{fmt, fmt::Display};
25 use tracing_error::SpanTrace;
27 pub type ConnectionId = usize;
29 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
30 pub struct IpAddr(pub String);
32 impl fmt::Display for IpAddr {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 write!(f, "{}", self.0)
39 macro_rules! location_info {
42 "None value at {}:{}, column {}",
50 #[derive(serde::Serialize)]
55 pub struct LemmyError {
56 pub message: Option<&'static str>,
57 pub inner: anyhow::Error,
58 pub context: SpanTrace,
62 /// Create LemmyError from a message, including stack trace
63 pub fn from_message(message: &'static str) -> Self {
64 let inner = anyhow::anyhow!("{}", message);
66 message: Some(message),
68 context: SpanTrace::capture(),
72 /// Create a LemmyError from error and message, including stack trace
73 pub fn from_error_message<E>(error: E, message: &'static str) -> Self
75 E: Into<anyhow::Error>,
78 message: Some(message),
80 context: SpanTrace::capture(),
84 /// Add message to existing LemmyError (or overwrite existing error)
85 pub fn with_message(self, message: &'static str) -> Self {
87 message: Some(message),
92 pub fn to_json(&self) -> Result<String, Self> {
93 let api_error = match self.message {
94 Some(error) => ApiError { error },
95 None => ApiError { error: "Unknown" },
98 Ok(serde_json::to_string(&api_error)?)
102 impl<T> From<T> for LemmyError
104 T: Into<anyhow::Error>,
106 fn from(t: T) -> Self {
110 context: SpanTrace::capture(),
115 impl std::fmt::Debug for LemmyError {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.debug_struct("LemmyError")
118 .field("message", &self.message)
119 .field("inner", &self.inner)
120 .field("context", &"SpanTrace")
125 impl Display for LemmyError {
126 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
127 if let Some(message) = self.message {
128 write!(f, "{}: ", message)?;
130 writeln!(f, "{}", self.inner)?;
135 impl actix_web::error::ResponseError for LemmyError {
136 fn status_code(&self) -> StatusCode {
137 match self.inner.downcast_ref::<diesel::result::Error>() {
138 Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
139 _ => StatusCode::BAD_REQUEST,
143 fn error_response(&self) -> HttpResponse {
144 if let Some(message) = &self.message {
145 HttpResponse::build(self.status_code()).json(ApiError { error: message })
147 HttpResponse::build(self.status_code())
148 .content_type("text/plain")
149 .body(self.inner.to_string())