Possible panic message improvement


#1

Given that we have std::error::Error (and it requires std::fmt::Display) would it be beneficial (and possible) to use Display when printing the cause of a panic instead of Debug?

The auto-generated Debug impl can be hard to digest for a complex struct.

Consider:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Parse { source: Some( "/home/mehcode/Workspace/config-rs/examples/file-toml/Settings.toml"), cause: Error { inner: ErrorInner { kind: NumberInvalid, line: Some(0), col: 8, message: "", key: [] } } }

Vs:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: invalid number at line 1 from ./Settings.toml

Now I can easily manually implement Debug to forward to Display but it feels odd enough that I thought I’d bring this up.

Thoughts?


#2

Display is intended for end-users, Debug for programmers. Panic is a programmer error, and is therefore intended for programmers, hence Debug.


#3

I wouldn’t agree that programmers want to see Debug in all cases. Especially with procedural macros using panics for error handling the easy path is to just unwrap errors. But most users of the procedural macro don’t want to see the Debug output of the error struct, they want to see the nice message the macro author(/macro’s dependency’s author) wrote for the error.

I ended up having to basically re-implement Result::expect using Display instead of Debug so that the error messages from my macro are usable for diagnosing why it’s failing, it could be useful to have an alternative expect method that prints out using Display, basically

impl<T, E> Result<T, E> where E: Display {
    fn nicely_expect(self, msg: &str) -> T {
        match self {
            Ok(ok) => ok,
            Err(err) => panic!("{}: {}", msg, err),
        }
    }
}

Although, this could be a niche use case where copy-pasting that tiny function to all macro crates is the best plan for now and we’ll get some sort of better error handling for proc-macros in the future.

I would agree that Result::unwrap should stick to Debug formatting only, I might use unwrap differently to most though as I try to treat it as a TODO that needs to either change to propagating the error or to an expect call with justification.