2023-07-10 14:50:07 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
2022-06-02 14:33:41 +00:00
|
|
|
use std::{
|
|
|
|
fmt,
|
|
|
|
fmt::{Debug, Display},
|
|
|
|
};
|
|
|
|
use tracing_error::SpanTrace;
|
2023-07-10 14:50:07 +00:00
|
|
|
#[cfg(feature = "full")]
|
|
|
|
use ts_rs::TS;
|
2022-06-02 14:33:41 +00:00
|
|
|
|
2023-04-13 00:17:23 +00:00
|
|
|
pub type LemmyResult<T> = Result<T, LemmyError>;
|
|
|
|
|
2022-06-02 14:33:41 +00:00
|
|
|
pub struct LemmyError {
|
2023-07-10 20:44:14 +00:00
|
|
|
pub error_type: LemmyErrorType,
|
2022-06-02 14:33:41 +00:00
|
|
|
pub inner: anyhow::Error,
|
|
|
|
pub context: SpanTrace,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> From<T> for LemmyError
|
|
|
|
where
|
|
|
|
T: Into<anyhow::Error>,
|
|
|
|
{
|
|
|
|
fn from(t: T) -> Self {
|
2023-07-10 20:44:14 +00:00
|
|
|
let cause = t.into();
|
2022-06-02 14:33:41 +00:00
|
|
|
LemmyError {
|
2023-07-10 20:44:14 +00:00
|
|
|
error_type: LemmyErrorType::Unknown(format!("{}", &cause)),
|
|
|
|
inner: cause,
|
2022-06-02 14:33:41 +00:00
|
|
|
context: SpanTrace::capture(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Debug for LemmyError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
f.debug_struct("LemmyError")
|
2023-07-10 14:50:07 +00:00
|
|
|
.field("message", &self.error_type)
|
2022-06-02 14:33:41 +00:00
|
|
|
.field("inner", &self.inner)
|
2023-05-12 00:12:12 +00:00
|
|
|
.field("context", &self.context)
|
2022-06-02 14:33:41 +00:00
|
|
|
.finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Display for LemmyError {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
2023-07-10 20:44:14 +00:00
|
|
|
write!(f, "{}: ", &self.error_type)?;
|
2023-06-30 13:32:43 +00:00
|
|
|
// print anyhow including trace
|
|
|
|
// https://docs.rs/anyhow/latest/anyhow/struct.Error.html#display-representations
|
|
|
|
// this will print the anyhow trace (only if it exists)
|
|
|
|
// and if RUST_BACKTRACE=1, also a full backtrace
|
|
|
|
writeln!(f, "{:?}", self.inner)?;
|
2022-06-02 14:33:41 +00:00
|
|
|
fmt::Display::fmt(&self.context, f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl actix_web::error::ResponseError for LemmyError {
|
|
|
|
fn status_code(&self) -> http::StatusCode {
|
|
|
|
match self.inner.downcast_ref::<diesel::result::Error>() {
|
|
|
|
Some(diesel::result::Error::NotFound) => http::StatusCode::NOT_FOUND,
|
|
|
|
_ => http::StatusCode::BAD_REQUEST,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn error_response(&self) -> actix_web::HttpResponse {
|
2023-07-10 20:44:14 +00:00
|
|
|
actix_web::HttpResponse::build(self.status_code()).json(&self.error_type)
|
2022-06-02 14:33:41 +00:00
|
|
|
}
|
|
|
|
}
|
2023-07-10 14:50:07 +00:00
|
|
|
|
|
|
|
#[derive(Display, Debug, Serialize, Deserialize, Clone, PartialEq, EnumIter)]
|
|
|
|
#[cfg_attr(feature = "full", derive(TS))]
|
|
|
|
#[cfg_attr(feature = "full", ts(export))]
|
|
|
|
#[serde(tag = "error", content = "message", rename_all = "snake_case")]
|
|
|
|
// TODO: order these based on the crate they belong to (utils, federation, db, api)
|
|
|
|
pub enum LemmyErrorType {
|
|
|
|
ReportReasonRequired,
|
|
|
|
ReportTooLong,
|
|
|
|
NotAModerator,
|
|
|
|
NotAnAdmin,
|
|
|
|
CantBlockYourself,
|
|
|
|
CantBlockAdmin,
|
|
|
|
CouldntUpdateUser,
|
|
|
|
PasswordsDoNotMatch,
|
|
|
|
EmailNotVerified,
|
|
|
|
EmailRequired,
|
|
|
|
CouldntUpdateComment,
|
|
|
|
CouldntUpdatePrivateMessage,
|
|
|
|
CannotLeaveAdmin,
|
|
|
|
NoLinesInHtml,
|
|
|
|
SiteMetadataPageIsNotDoctypeHtml,
|
|
|
|
PictrsResponseError(String),
|
|
|
|
PictrsPurgeResponseError(String),
|
2023-08-31 14:36:39 +00:00
|
|
|
PictrsCachingDisabled,
|
2023-07-10 14:50:07 +00:00
|
|
|
ImageUrlMissingPathSegments,
|
|
|
|
ImageUrlMissingLastPathSegment,
|
|
|
|
PictrsApiKeyNotProvided,
|
|
|
|
NoContentTypeHeader,
|
|
|
|
NotAnImageType,
|
|
|
|
NotAModOrAdmin,
|
|
|
|
NoAdmins,
|
|
|
|
NotTopAdmin,
|
|
|
|
NotTopMod,
|
|
|
|
NotLoggedIn,
|
|
|
|
SiteBan,
|
|
|
|
Deleted,
|
|
|
|
BannedFromCommunity,
|
|
|
|
CouldntFindCommunity,
|
|
|
|
CouldntFindPerson,
|
|
|
|
PersonIsBlocked,
|
|
|
|
DownvotesAreDisabled,
|
|
|
|
InstanceIsPrivate,
|
2023-10-05 11:40:22 +00:00
|
|
|
/// Password must be between 10 and 60 characters
|
2023-07-10 14:50:07 +00:00
|
|
|
InvalidPassword,
|
|
|
|
SiteDescriptionLengthOverflow,
|
|
|
|
HoneypotFailed,
|
|
|
|
RegistrationApplicationIsPending,
|
|
|
|
CantEnablePrivateInstanceAndFederationTogether,
|
|
|
|
Locked,
|
|
|
|
CouldntCreateComment,
|
|
|
|
MaxCommentDepthReached,
|
|
|
|
NoCommentEditAllowed,
|
|
|
|
OnlyAdminsCanCreateCommunities,
|
|
|
|
CommunityAlreadyExists,
|
|
|
|
LanguageNotAllowed,
|
|
|
|
OnlyModsCanPostInCommunity,
|
|
|
|
CouldntUpdatePost,
|
|
|
|
NoPostEditAllowed,
|
|
|
|
CouldntFindPost,
|
|
|
|
EditPrivateMessageNotAllowed,
|
|
|
|
SiteAlreadyExists,
|
|
|
|
ApplicationQuestionRequired,
|
|
|
|
InvalidDefaultPostListingType,
|
|
|
|
RegistrationClosed,
|
|
|
|
RegistrationApplicationAnswerRequired,
|
|
|
|
EmailAlreadyExists,
|
|
|
|
FederationForbiddenByStrictAllowList,
|
|
|
|
PersonIsBannedFromCommunity,
|
|
|
|
ObjectIsNotPublic,
|
|
|
|
InvalidCommunity,
|
|
|
|
CannotCreatePostOrCommentInDeletedOrRemovedCommunity,
|
|
|
|
CannotReceivePage,
|
|
|
|
NewPostCannotBeLocked,
|
|
|
|
OnlyLocalAdminCanRemoveCommunity,
|
|
|
|
OnlyLocalAdminCanRestoreCommunity,
|
|
|
|
NoIdGiven,
|
|
|
|
IncorrectLogin,
|
|
|
|
InvalidQuery,
|
|
|
|
ObjectNotLocal,
|
|
|
|
PostIsLocked,
|
2023-08-16 09:36:58 +00:00
|
|
|
PersonIsBannedFromSite(String),
|
2023-07-10 14:50:07 +00:00
|
|
|
InvalidVoteValue,
|
|
|
|
PageDoesNotSpecifyCreator,
|
|
|
|
PageDoesNotSpecifyGroup,
|
|
|
|
NoCommunityFoundInCc,
|
|
|
|
NoEmailSetup,
|
|
|
|
EmailSmtpServerNeedsAPort,
|
|
|
|
MissingAnEmail,
|
|
|
|
RateLimitError,
|
|
|
|
InvalidName,
|
|
|
|
InvalidDisplayName,
|
|
|
|
InvalidMatrixId,
|
|
|
|
InvalidPostTitle,
|
|
|
|
InvalidBodyField,
|
|
|
|
BioLengthOverflow,
|
|
|
|
MissingTotpToken,
|
2023-09-20 14:49:54 +00:00
|
|
|
MissingTotpSecret,
|
2023-07-10 14:50:07 +00:00
|
|
|
IncorrectTotpToken,
|
|
|
|
CouldntParseTotpSecret,
|
2023-09-20 14:49:54 +00:00
|
|
|
CouldntGenerateTotp,
|
|
|
|
TotpAlreadyEnabled,
|
2023-07-10 14:50:07 +00:00
|
|
|
CouldntLikeComment,
|
|
|
|
CouldntSaveComment,
|
|
|
|
CouldntCreateReport,
|
|
|
|
CouldntResolveReport,
|
|
|
|
CommunityModeratorAlreadyExists,
|
|
|
|
CommunityUserAlreadyBanned,
|
|
|
|
CommunityBlockAlreadyExists,
|
|
|
|
CommunityFollowerAlreadyExists,
|
|
|
|
CouldntUpdateCommunityHiddenStatus,
|
|
|
|
PersonBlockAlreadyExists,
|
|
|
|
UserAlreadyExists,
|
|
|
|
TokenNotFound,
|
|
|
|
CouldntLikePost,
|
|
|
|
CouldntSavePost,
|
|
|
|
CouldntMarkPostAsRead,
|
|
|
|
CouldntUpdateCommunity,
|
|
|
|
CouldntUpdateReplies,
|
|
|
|
CouldntUpdatePersonMentions,
|
|
|
|
PostTitleTooLong,
|
|
|
|
CouldntCreatePost,
|
|
|
|
CouldntCreatePrivateMessage,
|
|
|
|
CouldntUpdatePrivate,
|
|
|
|
SystemErrLogin,
|
|
|
|
CouldntSetAllRegistrationsAccepted,
|
|
|
|
CouldntSetAllEmailVerified,
|
|
|
|
Banned,
|
|
|
|
CouldntGetComments,
|
|
|
|
CouldntGetPosts,
|
|
|
|
InvalidUrl,
|
|
|
|
EmailSendFailed,
|
|
|
|
Slurs,
|
|
|
|
CouldntFindObject,
|
2023-10-04 13:20:22 +00:00
|
|
|
RegistrationDenied(Option<String>),
|
2023-07-10 14:50:07 +00:00
|
|
|
FederationDisabled,
|
2023-07-25 17:26:54 +00:00
|
|
|
DomainBlocked(String),
|
|
|
|
DomainNotInAllowList(String),
|
2023-07-10 14:50:07 +00:00
|
|
|
FederationDisabledByStrictAllowList,
|
|
|
|
SiteNameRequired,
|
|
|
|
SiteNameLengthOverflow,
|
|
|
|
PermissiveRegex,
|
|
|
|
InvalidRegex,
|
|
|
|
CaptchaIncorrect,
|
|
|
|
PasswordResetLimitReached,
|
|
|
|
CouldntCreateAudioCaptcha,
|
|
|
|
InvalidUrlScheme,
|
|
|
|
CouldntSendWebmention,
|
2023-08-08 09:40:28 +00:00
|
|
|
ContradictingFilters,
|
2023-09-20 09:56:13 +00:00
|
|
|
InstanceBlockAlreadyExists,
|
2023-08-29 14:47:57 +00:00
|
|
|
AuthCookieInsecure,
|
2023-07-10 20:44:14 +00:00
|
|
|
Unknown(String),
|
2023-07-10 14:50:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl From<LemmyErrorType> for LemmyError {
|
|
|
|
fn from(error_type: LemmyErrorType) -> Self {
|
|
|
|
let inner = anyhow::anyhow!("{}", error_type);
|
|
|
|
LemmyError {
|
2023-07-10 20:44:14 +00:00
|
|
|
error_type,
|
2023-07-10 14:50:07 +00:00
|
|
|
inner,
|
|
|
|
context: SpanTrace::capture(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub trait LemmyErrorExt<T, E: Into<anyhow::Error>> {
|
|
|
|
fn with_lemmy_type(self, error_type: LemmyErrorType) -> Result<T, LemmyError>;
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T, E: Into<anyhow::Error>> LemmyErrorExt<T, E> for Result<T, E> {
|
|
|
|
fn with_lemmy_type(self, error_type: LemmyErrorType) -> Result<T, LemmyError> {
|
|
|
|
self.map_err(|error| LemmyError {
|
2023-07-10 20:44:14 +00:00
|
|
|
error_type,
|
2023-07-10 14:50:07 +00:00
|
|
|
inner: error.into(),
|
|
|
|
context: SpanTrace::capture(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
pub trait LemmyErrorExt2<T> {
|
|
|
|
fn with_lemmy_type(self, error_type: LemmyErrorType) -> Result<T, LemmyError>;
|
2023-09-09 16:25:03 +00:00
|
|
|
fn into_anyhow(self) -> Result<T, anyhow::Error>;
|
2023-07-10 14:50:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> LemmyErrorExt2<T> for Result<T, LemmyError> {
|
|
|
|
fn with_lemmy_type(self, error_type: LemmyErrorType) -> Result<T, LemmyError> {
|
|
|
|
self.map_err(|mut e| {
|
2023-07-10 20:44:14 +00:00
|
|
|
e.error_type = error_type;
|
2023-07-10 14:50:07 +00:00
|
|
|
e
|
|
|
|
})
|
|
|
|
}
|
2023-09-09 16:25:03 +00:00
|
|
|
// this function can't be an impl From or similar because it would conflict with one of the other broad Into<> implementations
|
|
|
|
fn into_anyhow(self) -> Result<T, anyhow::Error> {
|
|
|
|
self.map_err(|e| e.inner)
|
|
|
|
}
|
2023-07-10 14:50:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2023-07-17 15:04:14 +00:00
|
|
|
#![allow(clippy::unwrap_used)]
|
|
|
|
#![allow(clippy::indexing_slicing)]
|
2023-07-10 14:50:07 +00:00
|
|
|
use super::*;
|
|
|
|
use actix_web::{body::MessageBody, ResponseError};
|
|
|
|
use std::fs::read_to_string;
|
|
|
|
use strum::IntoEnumIterator;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn deserializes_no_message() {
|
|
|
|
let err = LemmyError::from(LemmyErrorType::Banned).error_response();
|
|
|
|
let json = String::from_utf8(err.into_body().try_into_bytes().unwrap().to_vec()).unwrap();
|
|
|
|
assert_eq!(&json, "{\"error\":\"banned\"}")
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn deserializes_with_message() {
|
2023-10-04 13:20:22 +00:00
|
|
|
let reg_banned = LemmyErrorType::PersonIsBannedFromSite(String::from("reason"));
|
|
|
|
let err = LemmyError::from(reg_banned).error_response();
|
2023-07-10 14:50:07 +00:00
|
|
|
let json = String::from_utf8(err.into_body().try_into_bytes().unwrap().to_vec()).unwrap();
|
|
|
|
assert_eq!(
|
|
|
|
&json,
|
2023-10-04 13:20:22 +00:00
|
|
|
"{\"error\":\"person_is_banned_from_site\",\"message\":\"reason\"}"
|
2023-07-10 14:50:07 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Check if errors match translations. Disabled because many are not translated at all.
|
|
|
|
#[test]
|
|
|
|
#[ignore]
|
|
|
|
fn test_translations_match() {
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct Err {
|
|
|
|
error: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
let translations = read_to_string("translations/translations/en.json").unwrap();
|
|
|
|
LemmyErrorType::iter().for_each(|e| {
|
|
|
|
let msg = serde_json::to_string(&e).unwrap();
|
|
|
|
let msg: Err = serde_json::from_str(&msg).unwrap();
|
|
|
|
let msg = msg.error;
|
|
|
|
assert!(translations.contains(&format!("\"{msg}\"")), "{msg}");
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|