Can I log and nicely display Panics?


#1

I’m very new to Rust. When a division by zero or other Panics like this happen, can I - in the released software product - have another way of displaying it? It should be logged and it shouldn’t require a console. So, what ultimate “exception handler” comes last which I can make do this?


#2

Perhaps this: https://doc.rust-lang.org/std/panic/fn.set_hook.html


#3

You can use catch_unwind - that said, you shouldn’t rely on this:

It is not recommended to use this function for a general try/catch mechanism. The Result type is more appropriate to use for functions that can fail on a regular basis. Additionally, this function is not guaranteed to catch all panics…

Basically, panics are supposed to represent errors that leave the application in an unrecoverable/undefined state. For example, if you divide by zero, that indicates that the possibility exists that the divisor will be zero, but you don’t have any logic there to handle that - rather than do something weird/unexpected, Rust just says “nope” and quits.

In other words, catch_unwind is a handy thing to have, but the ideal solution to panics is to make sure they don’t happen in the first place :slight_smile:


#4

The problem is that in real world everyone seems to write banana software. The user tells that the app said “no no” and only then the programmer adds the check. I just quickly checked the set_hook API docs I couldn’t find anything to get a string of the backtrace. This would be a superb addition that would fit into the 2017 roadmap maybe. At least I have just today seen someone posting a crash dump that was catched by a Windows C++ application, ready to be pasted into a bug tracker in the web browser.


#5

https://crates.io/crates/backtrace


#6

I’ll have enough time to find out the usage until my app would need such a panic handler for releases. It’s good to know it’s possible. Thank you so much, you guys provide great support. :relaxed:


#7

I made a crate to do this! https://crates.io/crates/log-panics