0

I find it difficult to understand what's wrong with the below code. I'm getting expected struct Vec, found enum Result error at Ok(from_cache), but I have adopted the code from https://github.com/platy/update-tracker/blob/843092708906063704442f352231bfbac5b06196/server/src/web/mod.rs#L216-L226

During web scraping, I'm trying to cache the content of the URL in the cache and trying to reuse it.

use std::error::Error;

#[tokio::main]
async fn main() ->  Result<(), Box<dyn Error>> {
    let url: &str = "https://example.com/";
    let html = match cacache::read("./cache", url).await? {
        Ok(from_cache) => String::from_utf8(from_cache),
        Err(_) => {
            let t_html = reqwest::get(url).await?.text().await?;
            cacache::write("./cache", url, &t_html).await?;
            t_html
        },
    };
    println!("html = {:?}", html);

    Ok(())
}

Here's the playground (but, it shows other errors due to missing dependencies). Can anyone please explain this or share any relevant guide to gather more information about this topic?

Rajesh
  • 17
  • 6

1 Answers1

3

Recall that the ? operator unwraps a Result (or Option) by propagating the Err (or None) case out of the current function. Therefore, this expression:

cacache::read("./cache", url).await?

Has type Vec<u8> as the ? operator has unwrapped the Result. If you want to handle errors yourself, then omit the ? operator:

cacache::read("./cache", url).await
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • I accepted your answer as it clears this particular issue. But, error now appears in subsequent lines at `String::from_utf8(from_cache)` with `this is found to be of type Result` and at `t_html` with `expected enum Result, found struct std::string::String` It clearly seems that I need to refer some good guides, but I can't seem to find anything for these. – Rajesh Apr 25 '22 at 18:21
  • 2
    @Rajesh `String::from_utf8` can fail on invalid encoding, so that also returns a `Result` which must be appropriately handled. If you _know_ that the conversion can't fail then you can `.unwrap()` it, which will panic if an error does occur. – cdhowie Apr 25 '22 at 18:28
  • Thank you. I'm still learning and trying it out – Rajesh Apr 25 '22 at 18:43
  • 1
    @Rajesh I'd suggest reading through the Rust book (linked in my answer) as it covers a lot of very useful topics that you might stumble over otherwise, particularly if you are coming from another programming language. – cdhowie Apr 25 '22 at 18:47