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, time::Duration};
25 use tracing_error::SpanTrace;
27 pub type ConnectionId = usize;
29 pub const REQWEST_TIMEOUT: Duration = Duration::from_secs(10);
31 #[derive(PartialEq, Eq, Hash, Debug, Clone)]
32 pub struct IpAddr(pub String);
34 impl fmt::Display for IpAddr {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 write!(f, "{}", self.0)
41 macro_rules! location_info {
44 "None value at {}:{}, column {}",
52 #[derive(serde::Serialize)]
57 pub struct LemmyError {
58 pub message: Option<String>,
59 pub inner: anyhow::Error,
60 pub context: SpanTrace,
64 /// Create LemmyError from a message, including stack trace
65 pub fn from_message(message: &str) -> Self {
66 let inner = anyhow::anyhow!("{}", message);
68 message: Some(message.into()),
70 context: SpanTrace::capture(),
74 /// Create a LemmyError from error and message, including stack trace
75 pub fn from_error_message<E>(error: E, message: &str) -> Self
77 E: Into<anyhow::Error>,
80 message: Some(message.into()),
82 context: SpanTrace::capture(),
86 /// Add message to existing LemmyError (or overwrite existing error)
87 pub fn with_message(self, message: &str) -> Self {
89 message: Some(message.into()),
94 pub fn to_json(&self) -> Result<String, Self> {
95 let api_error = match &self.message {
96 Some(error) => ApiError {
100 error: "Unknown".into(),
104 Ok(serde_json::to_string(&api_error)?)
108 impl<T> From<T> for LemmyError
110 T: Into<anyhow::Error>,
112 fn from(t: T) -> Self {
116 context: SpanTrace::capture(),
121 impl std::fmt::Debug for LemmyError {
122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 f.debug_struct("LemmyError")
124 .field("message", &self.message)
125 .field("inner", &self.inner)
126 .field("context", &"SpanTrace")
131 impl Display for LemmyError {
132 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
133 if let Some(message) = &self.message {
134 write!(f, "{}: ", message)?;
136 writeln!(f, "{}", self.inner)?;
141 impl actix_web::error::ResponseError for LemmyError {
142 fn status_code(&self) -> StatusCode {
143 match self.inner.downcast_ref::<diesel::result::Error>() {
144 Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
145 _ => StatusCode::BAD_REQUEST,
149 fn error_response(&self) -> HttpResponse {
150 if let Some(message) = &self.message {
151 HttpResponse::build(self.status_code()).json(ApiError {
152 error: message.into(),
155 HttpResponse::build(self.status_code())
156 .content_type("text/plain")
157 .body(self.inner.to_string())