Code has started to panic

[This is not problem. The question is just for fun, for selfstudiing]

async fn my_api() -> Result<String, reqwest::Error> {
    reqwest::get(   MY_URL_2    )
        .await?
        .text()
        .await  
}


HERE NOTHING HAPPENED WHEN INTERNET CONNECTION IS NOT ESTABLISHED
IT WAS NICE
my_ips.ip = my_api().await.unwrap() .parse().unwrap(); 



BUT NOW, IT RAISES A PANIC IF INTERNET CONNECTION IS NOT ESTABLISHED
(AFTER UPDATING RUST, DEPENDENCIES OR MAYBE IT SEEMS MY CODE EDITING )
SO NOW I HAVE TO CHECK IS THERE THE INTERNET CONNECTION
if &  my_ips.isp != & std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST) {
        my_ips.ip = my_api().await.unwrap() .parse().unwrap(); 
}

Is it OK ?
It would be nice to restore first behave...

[dependencies]
chrono = "0.4"
reqwest = "0.11"
tokio = { version = "1.33.0" , features = [ "full" ] }
local-ip-address = "0.5.5"

thread 'main' panicked at src\main.rs:57:39:
called `Result::unwrap()` on an `Err` value: reqwest::Error { kind: Request, url: Url { scheme: "https", cannot_be_a_base: false, username: "", password: None, host: Some(Domain("api64.ipify.org")), port: None, path: "/", query: Some("format=text"), fragment: None }, source: hyper::Error(Connect, ConnectError("dns error", Os { code: 11001, kind: Uncategorized, message: ".....

.unwrap() is asking the program to panic. Do not use it.

You should use the ? operator, or match, or if let Err if you want errors handled gracefully.

3 Likes

You're also setting yourself up for TOCTOU. There's a great many (additional) things that could go wrong when fetching a URL and you can't really pre-check most of them (even if it wasn't a race condition), so just try to fetch and then see if it worked.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.