Skip to content

About how to try_get_with() Arc<Error> #245

Answered by tatsuya6502
Cloud33 asked this question in Q&A
Discussion options

You must be logged in to vote

Hi.

I don't know how to convert Arc into an Error and return it to the front-end

If your error type Error implements Clone trait, you can create Error from Arc<Error> by cloning it:

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, Arc provides try_unwrap method, which returns the inner value if the Arc has exactly one strong reference. So you can do …

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Cloud33
Comment options

Answer selected by Cloud33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants