Return an anyhow error from Display trait implementation

I am implementing the Display trait for a type like so:

impl Display for Key {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let modifier = match self.0.modifiers {
            KeyModifiers::ALT => Some("alt"),
            KeyModifiers::CONTROL => Some("ctrl"),
            KeyModifiers::NONE => None,
            invalid => bail!("Invalid key modifier provided in keybinding: {:?}", invalid),
        };
    ...

However, the bail! fails because it expects to return an anyhow::Error instead of the required std::format::Error. Any way I can modify the return Result to be an anyhow error? Or another way to solve this?

No.

return Err(core::fmt::Error);


However, this is ill-advised. Display::fmt() should only return an error when formatting itself fails for some reason; things like .to_string() basically assume it to never fail except under apocalyptic conditions. If your modifier enum is too broad, convert it fallibly to a narrower set upfront.

3 Likes

Ok, thanks, that's a good point that Display::fmt() should practically never fail, I'll make some design changes to account for that.

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.