0

So I have a multi-threading program in Rust, which sends Get Requests to my Website, and I'm wondering how I can detect a ConnectionReset. What I'm trying to do is, after the request, check if there was a ConnectionReset, and if there was, wait for a minute, so the thread doesn't panic

The code I'm using right now

let mut req = reqwest::get(&url).unwrap();

And after that was executed I want to check if there's a ConnectionReset, and then println ("Connection Error"), instead of having the thread panic.

The Error, that I want to detect

thread '<unnamed>' panicked at 'called `Result::unwrap()` on an `Err` value: 
Error { kind: Io(Custom { kind: Other, error: Os { code: 10054, kind: ConnectionReset, 
message: "An existing connection was forcibly closed by the remote host." } }), 
url: Some("https://tayhay.vip") }', src\main.rs:22:43

I also read something about std::panic::catch_unwind, but I am not sure if that's the right way to go.

Tayhay
  • 3
  • 3

1 Answers1

1

.unwrap means literally: "panic in case of error". If you don't want to panic, you will have to handle the error yourself. You have three solutions here depending on code you haven't shown us:

  1. Propagate the error up with the ? operator and let the calling function handle it.
  2. Have some default value ready to use (or create on the fly) in case of error:
let mut req = reqwest::get (&url).unwrap_or (default);

or

let mut req = reqwest::get (&url).unwrap_or_else (|_| { default });

(this probably doesn't apply in this specific case since I don't know what would make a sensible default here, but it applies in other error handling situations).

  1. Have some specific error handling code:
match reqwest::get (&url) {
   Ok (mut req) => { /* Process the request */ },
   Err (e) => { /* Handle the error */ },
}

For more details, the Rust book has a full chapter on error handling.

Jmb
  • 18,893
  • 2
  • 28
  • 55