Nano_get handle error

Hello, I'm trying to handle request error of nano_get crate

let request = nano_get::Request::default_get_request("https:/test.com").expect("Failed to open request");
let response: Response = match request.execute() {
     Ok(x) => Some(x), // <- take out only the value
     Err(err) => Some(err),
     };

but I receive this error:
expected struct nano_get::Response, found enum std::option::Option

How can I handle error?

In your Ok branch of the match, x is what has type Response, so if you return Some(x), you have an Option<Response>.

ok thanks and how can I handle Err?

Well what do you want to happen if it fails? It can look like this:

let response: Response = match request.execute() {
    Ok(x) => x,
    Err(err) => {
         // handle the error here
    }
};

If your function returns a result, you can use the question mark operator, which will immediately return the error if it fails:

let response = request.execute()?;

You can also simply panic on error:

let response = request.execute().unwrap(); // kill program if fails

If I try this

let response: Response = match request.execute() {
                Ok(x) => x,
                Err(err) => {
                    // handle the error here
                    println!("{:?}", err);
                }
            };

I receive:
Err(err) => {
| ____________^
308 | | // handle the error here
309 | | println!("{:?}", err);
310 | | }
| |
^ expected struct nano_get::Response, found ()

I don't want to kill program if fail but I want only a message

thanks

It fails because it doesn't know how to continue after your println!. You probably want a return after the print.

1 Like

I want only that if get fails don't crash. So in your opinion I have to simulate a Response type if fail?

Simulating a response sounds kinda sketchy. Do you have a meaningful response value to use if your http request fails?

No I don't

What do you want your program to do if the request fails?

if it's ok I get response.body if fails I want only a custom response.body with a string for example

So you do have a meaningful response value, one that has a certain string?

yes

Then you can return that after your print.

let response: Response = match request.execute() {
    Ok(x) => x,
    Err(err) => {
         println!("oops: {}", err);
         my_meaningful_response
    }
};

how can I simulate my response? response.body is a string but I think it expects a response type

I'm not too familiar with nano-get, but it looks like you can't create a Response object manually.

If I use reqwest do you think I can solve this problem?

Probably not. You will probably have to find some other solution.

1 Like

My program must check the connection to a server every few seconds (60). If the connection fails, you just have to show it and not kill it. Have you an idea?

You could return from the function on failure, and have a loop outside the function that will call it again 60 seconds later?