本文介绍了使用panic :: catch_unwind时抑制Rust中的panic输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用引起恐慌:
I'm using panic::catch_unwind
to catch a panic:
use std::panic;
fn main() {
let result = panic::catch_unwind(|| {
panic!("test panic");
});
match result {
Ok(res) => res,
Err(_) => println!("caught panic!"),
}
}
( )
这似乎工作得很好,但是我仍然将恐慌的输出传递到stdout。我希望只打印出此内容:
This seems to work just fine, but I am still getting the output of the panic to stdout. I'd like this to only print out:
caught panic!
代替
thread '<main>' panicked at 'test panic', <anon>:6
note: Run with `RUST_BACKTRACE=1` for a backtrace.
caught panic!
推荐答案
您需要注册紧急钩子和什么也不做。然后,您可以使用:
You need to register a panic hook with std::panic::set_hook
that does nothing. You can then catch it with std::panic::catch_unwind
:
use std::panic;
fn main() {
panic::set_hook(Box::new(|_info| {
// do nothing
}));
let result = panic::catch_unwind(|| {
panic!("test panic");
});
match result {
Ok(res) => res,
Err(_) => println!("caught panic!"),
}
}
As ,您可以获取最新的与 std :: panic :: take_hook
,以便以后恢复它。
As Matthieu M. notes, you can get the current hook with std::panic::take_hook
in order to restore it afterwards, if you need to.
另请参见:
- Redirect panics to a specified buffer
这篇关于使用panic :: catch_unwind时抑制Rust中的panic输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!