简体   繁体   中英

A Rust function return a future, after .await(), it may be throw a panic!. How can I avoid the panic! to stop the program?

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();
    }

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),
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM