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 pub fn from_message(message: &'static str) -> Self {
63 let inner = anyhow::anyhow!("{}", message);
65 message: Some(message),
67 context: SpanTrace::capture(),
70 pub fn with_message(self, message: &'static str) -> Self {
72 message: Some(message),
76 pub fn to_json(&self) -> Result<String, Self> {
77 let api_error = match self.message {
78 Some(error) => ApiError { error },
79 None => ApiError { error: "Unknown" },
82 Ok(serde_json::to_string(&api_error)?)
86 impl<T> From<T> for LemmyError
88 T: Into<anyhow::Error>,
90 fn from(t: T) -> Self {
94 context: SpanTrace::capture(),
99 impl std::fmt::Debug for LemmyError {
100 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 f.debug_struct("LemmyError")
102 .field("message", &self.message)
103 .field("inner", &self.inner)
104 .field("context", &"SpanTrace")
109 impl Display for LemmyError {
110 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
111 if let Some(message) = self.message {
112 write!(f, "{}: ", message)?;
114 writeln!(f, "{}", self.inner)?;
119 impl actix_web::error::ResponseError for LemmyError {
120 fn status_code(&self) -> StatusCode {
121 match self.inner.downcast_ref::<diesel::result::Error>() {
122 Some(diesel::result::Error::NotFound) => StatusCode::NOT_FOUND,
123 _ => StatusCode::BAD_REQUEST,
127 fn error_response(&self) -> HttpResponse {
128 if let Some(message) = &self.message {
129 HttpResponse::build(self.status_code()).json(ApiError { error: message })
131 HttpResponse::build(self.status_code())
132 .content_type("text/plain")
133 .body(self.inner.to_string())