[英]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.我正在制作 function call_data()
,它将返回一个未来。 In the main function, I use tokio task to call call_data()
forever each 60 seconds.在主 function 中,我使用 tokio 任务每 60 秒永久调用call_data()
。 Some time, the call_data()
.await is a Error, so there is a panic.有时, call_data()
.await 是一个错误,所以会出现恐慌。 and stop the program.并停止程序。 I try let a = call_data("name", "table").await;
我尝试let a = call_data("name", "table").await;
, then use match
, if Ok
, future is excuted, if Error
, continue. , 然后使用match
,如果Ok
,future 被执行,如果Error
,继续。 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
这是我使用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您的 fn call_data
应该类似于
async fn call_data(name: &str, table: &str) -> std::result::Result<Data, Box<dyn error::Error>> {
Ok(Data {})
}
and match
should look like和match
应该看起来像
match call_data("", "").await {
Ok(data) => {
// do something with data
},
Err(e) => println!("Error: {:?}", e),
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.