How do I ban unwrap and expect function?

I'm writing a program that will run under a process manager that doesn't catch stderr and stdout, so I want to force everyone to not use unwrap() and expect() and use our own unwrap_logging() and expect_logging() instead that will do the same thing but sends its error message to syslog. Is there a way to ban those functions, something like #[deny(unwrap,expect)] ?

As an alternative, which I've not used I just know it exists, you could hook the panic handler since both unwrap and expect (in addition to any other panic), should pass through it. std::panic::set_hook - Rust


Clippy has a lint for unwrap called unwrap_used. You can deny it with #![deny(clippy::unwrap_used)], although it will only trigger when running clippy and not when compiling normally. There's also an expect_used.


I think @Cocalus's advise is a better alternative since except and unwrap is not the only methods that panic and write to the stderr.

I also prefer @Cocalus solution, but is it safe? What happens if my logging function panic!s while that same logging function is hooked to the panic handler? Will it enter some sort of infinite loop?

It should abort the process the same as panicking during an unwind. Which is memory safe (the process dies before potentially violating memory safety), but it still kills the process.

It's far easier to to avoid any panicking code within just your error logger, than all panics in the rest of the code. indexing a collection can panic among many other things.

let v = vec![1];
let oops = v[2];

Most panicking calls have an Option or Result variant, for the above that would be v.get(2) so try to use the none panicking functions within your logger.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.