thiserror icon indicating copy to clipboard operation
thiserror copied to clipboard

Add example for expressions in `error` attribute

Open dnaka91 opened this issue 3 years ago • 3 comments

Hi @dtolnay, that you so much for this awesome crate. I use it everywhere all the time (together with anyhow).

Was trying to figure out how to nicely display an Option<T> value in the error message, instead of just using {0:?} and having Some("...")/None in the displayed message.

So I found a nice test case in tests/test_display.rs, and thought it might be nice to add a tiny example to the README.md and crate docs, to showcase that expressions are possible in the #[error("...")] attribute as well.

Wording of the example could maybe be a bit improved, I'm not as good of a writer as you 🙇‍♂️.

dnaka91 avatar Jul 19 '22 06:07 dnaka91

@dnaka91 thank you! I came here for exactly this reason. I have an error that comes from an API which always includes an error code and usually but not always includes a clarifying error message. Your example helped me a lot.

bjeanes avatar Aug 29 '22 21:08 bjeanes

I'm happy to change my initial sample to something more elaborate. My case was really something that simple where I just wanted to avoid the Some("...")/None as part of the error message.

How about something like a PathBuf + std::io::Error that matches on the error kinds to give nicer messages than the default I/O error implementation?

Of course would be interested in the code from @bjeanes too.

dnaka91 avatar Sep 30 '22 16:09 dnaka91

Thanks for the bump. I saw the previous notification but got sidetracked digging up my example and forgot!

I have some code which works with an API which returns error payloads like {"code": 301, "message": "read failed"}. The error codes are totally undocumented and only some of them include a message field.

So, my error to represent these looks like this:

#[error("{code}{}", match .message {
    Some(msg) => format!(" - {}", &msg),
    None => "".to_owned(),
})]
SungrowError { code: u16, message: Option<String> },

bjeanes avatar Sep 30 '22 21:09 bjeanes