Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return empty String if match fails in function

I have a function like this

fn get_html(address: &str) -> String {
    let mut response = reqwest::blocking::get(
        address,
    );

    response = response.unwrap_or_else(|_e| {String::from("")});
    response = response.text().unwrap_or_else(|_e| {String::from("")});
    return response
    }

Where I’m checking for html content. I would like to return an empty String if any kind of an error occurs somewhere in this function.
I’m not sure how to deal with this because unwrap_or_else expecting Result not String.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reqwest::blocking::get() function is returning a Result<Response>.

To obtain the html, you have to unwrap this result and call .text() method.

That will return a Result<String>, that you have to unwrap again.

In your code you assign a String::from("") when you unwrap the Result<Response>, and that is not right, because you have a Response when it is Ok and a String when it is an Err.

Instead you should match the result and return the String from the function:

fn get_html(address: &str) -> String {
    let mut response = reqwest::blocking::get(
        address,
    );

    match response {
        Ok(response) => response.text().unwrap_or_else(|_e| String::from("")),
        Err(_) => String::from(""),
   }
}

In this code, you use unwrap_or_else() just on the .text() result.
While if you have an error on the response itself, you return a String from the function.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading