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<&'static str>,
59 pub inner: anyhow::Error,
60 pub context: SpanTrace,
64 /// Create LemmyError from a message, including stack trace
65 pub fn from_message(message: &'static str) -> Self {
66 let inner = anyhow::anyhow!("{}", message);
68 message: Some(message),
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: &'static str) -> Self
77 E: Into<anyhow::Error>,
80 message: Some(message),
82 context: SpanTrace::capture(),
86 /// Add message to existing LemmyError (or overwrite existing error)
87 pub fn with_message(self, message: &'static str) -> Self {
89 message: Some(message),
94 pub fn to_json(&self) -> Result<String, Self> {
95 let api_error = match self.message {
96 Some(error) => ApiError { error },
97 None => ApiError { error: "Unknown" },
100 Ok(serde_json::to_string(&api_error)?)
104 impl<T> From<T> for LemmyError
106 T: Into<anyhow::Error>,
108 fn from(t: T) -> Self {
112 context: SpanTrace::capture(),
117 impl std::fmt::Debug for LemmyError {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 f.debug_struct("LemmyError")
120 .field("message", &self.message)
121 .field("inner", &self.inner)
122 .field("context", &"SpanTrace")
127 impl Display for LemmyError {
128 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
129 if let Some(message) = self.message {
130 write!(f, "{}: ", message)?;
132 writeln!(f, "{}", self.inner)?;
137 impl actix_web::error::ResponseError for LemmyError {
138 fn status_code(&self) -> StatusCode {
139 match self.inner.downcast_ref::<diesel::result::Error>() {
140 Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
141 _ => StatusCode::BAD_REQUEST,
145 fn error_response(&self) -> HttpResponse {
146 if let Some(message) = &self.message {
147 HttpResponse::build(self.status_code()).json(ApiError { error: message })
149 HttpResponse::build(self.status_code())
150 .content_type("text/plain")
151 .body(self.inner.to_string())