It may be not a good idea or not idiomatic, but let's assume that for some reason a library relies on catch_unwind
for its business logic.
Can I somehow warn (by failing the compilation with an error message?) a user of this library if they set panic = "abort"
in Cargo.toml
of their "terminal" crate?
I was thinking about checking some environment variable in build.rs
but can't find any variables with this information.
The panic! macro signals that your program is in a state it can't handle and lets you tell the process to stop instead of trying to proceed with invalid or incorrect values. The Result enum uses Rust's type system to indicate that operations might fail in a way that your code could recover from.
The behavior of the default std hook, i.e. the code that runs directly after the panic is invoked, is to print the message payload to stderr along with the file/line/column information of the panic!() call. You can override the panic hook using std::panic::set_hook() .
You can use this unstable code in your binary or library to cause an error when -C panic=abort
is specified:
#![feature(panic_unwind)]
extern crate panic_unwind;
Which causes this helpful error when the wrong panic strategy is used:
error: the linked panic runtime `panic_unwind` is not compiled with this crate's panic strategy `abort`
When the panic strategy is correct, the extern crate
declaration is redundant, but does nothing. When the panic strategy is wrong, it causes a linking error since you can't have two different panic strategy crates in the same binary. Since this check happens when crates are linked, note that if a library is never actually used by the top-level crate, then the check isn't run. (but this is a good thing: if your library is unused, then there is no need for this check anyways!)
Also, this error happens very late in the compilation process, so while cargo build
will error out, cargo check
won't complain since cargo check
doesn't check for linking errors for performance reasons.
Unfortunately, there doesn't seem to be a way to do this on the stable channel.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With