Simplify handling of NotFound SQL errors (fixes #4633)

This commit is contained in:
Felix Ableitner 2024-09-19 15:21:15 +02:00
parent 026e23cf32
commit 4b250cfe08
3 changed files with 21 additions and 5 deletions

View file

@ -40,10 +40,7 @@ pub async fn get_post(
};
// Check to see if the person is a mod or admin, to show deleted / removed
let community_id = Post::read(&mut context.pool(), post_id)
.await?
.ok_or(LemmyErrorType::CouldntFindPost)?
.community_id;
let community_id = Post::read_xx(&mut context.pool(), post_id).await?.community_id;
let is_mod_or_admin = is_mod_or_admin_opt(
&mut context.pool(),

View file

@ -68,6 +68,10 @@ impl Crud for Post {
}
impl Post {
pub async fn read_xx(pool: &mut DbPool<'_>, id: PostId) -> Result<Self, Error> {
let conn = &mut *get_conn(pool).await?;
post::table.find(id).first(conn).await
}
pub async fn insert_apub(
pool: &mut DbPool<'_>,
timestamp: DateTime<Utc>,

View file

@ -211,8 +211,12 @@ cfg_if! {
{
fn from(t: T) -> Self {
let cause = t.into();
let error_type = match cause.downcast_ref::<diesel::result::Error>() {
Some(&diesel::NotFound) => LemmyErrorType::CouldntFindPost,
_ => LemmyErrorType::Unknown(format!("{}", &cause))
};
LemmyError {
error_type: LemmyErrorType::Unknown(format!("{}", &cause)),
error_type,
inner: cause,
context: Backtrace::capture(),
}
@ -323,6 +327,17 @@ cfg_if! {
)
}
#[test]
fn test_convert_diesel_errors() {
let not_found_error = LemmyError::from(diesel::NotFound);
assert_eq!(LemmyErrorType::CouldntFindPost, not_found_error.error_type);
assert_eq!(404, not_found_error.status_code());
let other_error = LemmyError::from(diesel::result::Error::NotInTransaction);
assert!(matches!(other_error.error_type, LemmyErrorType::Unknown{..}));
assert_eq!(400, other_error.status_code());
}
/// Check if errors match translations. Disabled because many are not translated at all.
#[test]
#[ignore]