About how to try_get_with() Arc<Error> #245
-
Hello, I am a Rust novice, I use I don't know how to handle the The code is probably: pub struct UserService{
pub db: DbPool,
pub cache: Cache<i64, Arc<User>>,
}
impl UserService{
async async fn get_cache(&self, id: i64) -> Result<Arc<User>, Error> {
//// error , return Arc<Error>
self.cache.try_get_with(proc_id, self.get(proc_id)).await
}
async fn get(&self, id: i64) -> Result<Arc<User>, Error> {
let user = self.db.read(id).await;
match proc {
Ok(proc) => Ok(Arc::new(user)),
Err(err) => Err(err),
}
}
}
thank you |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi.
If your error type use thiserror::Error;
#[derive(Error, Debug, Clone)]
pub enum MyError {
#[error("db error")]
DbError,
}
impl UserService {
async fn get_cache(&self, id: i64) -> Result<Arc<User>, MyError> {
self.cache
.try_get_with(id, self.get(id))
.await
// Create `MyError` from `Arc<MyError>`.
.map_err(|e| (*e).clone())
}
} Also, /// Tries to unwrap the `Arc<T>` and returns the original `T` if successful.
/// Otherwise, returns a clone of the original `T`.
pub(crate) fn unwrap_arc_or_clone<T: Clone>(v: Arc<T>) -> T {
Arc::try_unwrap(v).unwrap_or_else(|v| (*v).clone())
}
impl UserService {
async fn get_cache(&self, id: i64) -> Result<Arc<User>, MyError> {
self.cache
.try_get_with(id, self.get(id))
.await
.map_err(unwrap_arc_or_clone)
}
} If your error type does not implement This should not be too bad because let e = Arc::new(MyError::DbError);
// You can call `source` method of `Error` trait on the `Arc` directly.
dbg!(e.source());
// You can also use `match` on the `Arc` as if it is `MyError`
// by dereferencing it.
match *e {
MyError::DbError => todo!(),
} |
Beta Was this translation helpful? Give feedback.
Hi.
If your error type
Error
implementsClone
trait, you can createError
fromArc<Error>
by cloning it:Also,
Arc
providestry_unwrap
method, which returns the inner value if theArc
has exactly one strong reference. So you can do …