0

I'm making a function call_data(), it will return a future. In the main function, I use tokio task to call call_data() forever each 60 seconds. Some time, the call_data().await is a Error, so there is a panic! and stop the program. I try let a = call_data("name", "table").await;, then use match, if Ok, future is excuted, if Error, continue. However, that is not work, if there is panic!, still throw the panic!. Do I have any ways to avoid the panic! for this program? Below is the code I do not using match!

async fn main() {
    let forever = task::spawn(async {
        let mut interval = interval(Duration::from_millis(60000));
        println!("Start");
        loop {
            interval.tick().await;
            call_data("name", "table").await;
        }
    });
    forever.await;
}

async fn call_data(name:&str, table: &str){
    data().unwrap();
}

This is the code I use match

async fn main() {
        let forever = task::spawn(async {
            let mut interval = interval(Duration::from_millis(60000));
            println!("Start");
            loop {
                let a =call_data("BTC-USD", "test3").await;
                match a{
                      Ok=>(),
                      Err=>continue,
                 }
            }
        });
        forever.await;
    }
    
    async fn call_data(name:&str, table: &str){
        data().unwrap();
    }
Lee Alex
  • 171
  • 2
  • 3
  • 13
  • `match`-ing on an error (or a similar method) instead of `unwrap()` is the intended way to avoid panics and handle errors gracefully. Why did it not work for you? If you paste the code you tried using `match` and the error you received, people would be able to help you easier. – justinas Nov 17 '21 at 21:17
  • @justinas, yes, I update the post. I put the match code inside! Thank s for your suggestion!!! – Lee Alex Nov 17 '21 at 21:24
  • 1
    As I can see in your code, `call_data` doesn't return `Result`, and panic probably occurs in `call_data` fn, because of `.unwrap()` – Đorđe Zeljić Nov 17 '21 at 21:49
  • 1
    Be sure to read the [documentation for `unwrap()`](https://doc.rust-lang.org/std/option/enum.Option.html#method.unwrap) and maybe [this answer](https://stackoverflow.com/a/36362163/574531) that explains what it does. You can't "catch" a `panic!`; you have to avoid creating one in the first place. – Herohtar Nov 17 '21 at 22:57

1 Answers1

0

Your fn call_data should look something like

async fn call_data(name: &str, table: &str) -> std::result::Result<Data, Box<dyn error::Error>> {
    Ok(Data {})
}

and match should look like

match call_data("", "").await {
    Ok(data) => {
        // do something with data
    },
    Err(e) => println!("Error: {:?}", e),
}
Đorđe Zeljić
  • 1,689
  • 2
  • 13
  • 30