Error enum fixed
Replaces #3304. There were a number of problems with that one, most importantly error responses being formatted incorrectly so that api tests would fail. Also some errors were renamed, eg "couldnt -> could not" which would break the api. This should all be fixed now.
I'll have to update the js client PR whenever this is merged.
this is great. maybe you could impl From<LemmyErrorType> for LemmyError though? so that all those LemmyError::from_type(LemmyErrorType::CantBlockAdmin) are shorter. then you should even be able to just use the ? operator on lemmyerrortype in many cases
You should also be able to make the from_error_and_type method an extension method on Into<anyhow::Error>, then this code:
PostRead::mark_as_unread(pool, &post_read_form)
.await
.map_err(|e| LemmyError::from_error_and_type(e, LemmyErrorType::CouldntMarkPostAsRead))
}
would look like the following:
PostRead::mark_as_unread(pool, &post_read_form)
.await
.with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)
}
Good idea, Ive implemented impl From<LemmyErrorType> for LemmyError and it really shortens t he code.
But I dont know how the extension method is supposed to work, Ive never used that before. I tried with this code:
pub trait WithLemmyType: Into<anyhow::Error> {
fn with_lemmy_type(self, error_type: LemmyErrorType) -> LemmyError {
LemmyError::from_error_and_type(self, error_type)
}
}
impl<T: Into<anyhow::Error>> WithLemmyType for T {}
And calling it exactly like in your example. But it fails with the following error, seems like the method should really take Result, but not sure how to do that.
)
error[E0599]: the method `with_lemmy_type` exists for enum `Result<usize, Error>`, but its trait bounds were not satisfied
--> crates/api_common/src/utils.rs:134:6
|
132 | / PostRead::mark_as_unread(pool, &post_read_form)
133 | | .await
134 | | .with_lemmy_type(LemmyErrorType::CouldntMarkPostAsRead)
| | -^^^^^^^^^^^^^^^ method cannot be called on `Result<usize, Error>` due to unsatisfied trait bounds
| |_____|
|
|
::: /home/felix/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/result.rs:503:1
here's a working extension trait:
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(|e| LemmyError::from_error_and_type(e, error_type))
}
}
it just has to extend Result<T, into anyhow> and not into
Thats it, got it all cleaned up now.