At the end, my blog post says this:
If you’re writing a library and your code can produce errors, define your own error type and implement the
std::error::Error
trait. Where appropriate, implementFrom
to make both your library code and the caller’s code easier to write.
The blog post contains at least a few examples of this.
Today, I would probably not use any error handling helper library for a library. Generally, I do not think defining your own errors requires that much boiler plate. Defining the error variants themselves, along with how to convert them and how to show them, are all important aspects of your public API. (And perhaps more importantly, paying careful attention to this is crucial for choosing what exactly you expose. It can be very easy to accidentally incur a public dependency on another library by re-exporting one of its errors or exposing a From
impl. It may instead make sense to not export such errors.) The "boiler plate" part of it is really the bits and pieces around it, e.g., writing out the impl From<...> for ... {}
, writing out the impl fmt::Display for ... { }
along with the corresponding match
expressions.
I've done this many times myself. Here are some of them: (Some of this code still contains impls of cause
or description
, but you can drop the latter, and should implement source
instead today, if pertinent.)
- https://github.com/BurntSushi/rust-csv/blob/366c07528af626318c1cc8c172e3242b7fe12570/src/error.rs#L28
- https://github.com/rust-lang/regex/blob/03b605be3c8df6c010095f2d8dd88a2bf0ec46f8/regex-syntax/src/hir/mod.rs#L34
- https://github.com/rust-lang/regex/blob/03b605be3c8df6c010095f2d8dd88a2bf0ec46f8/regex-syntax/src/ast/mod.rs#L33
- https://github.com/BurntSushi/regex-automata/blob/ffefcf61c1c6505ece70e6d629597c8cf22d7466/src/error.rs#L11
- https://github.com/BurntSushi/aho-corasick/blob/c36b2614bbeb972022540f0443fc1424cd86ede7/src/error.rs#L10
- https://github.com/BurntSushi/rust-pcre2/blob/09a7b7e600bb5c2ed95802d9a4774cc32d58ae19/src/error.rs#L13
- https://github.com/BurntSushi/rust-snappy/blob/ba7e0ba6ee8cab026753849f9dba56f7853899ac/src/error.rs#L78
- https://github.com/BurntSushi/ucd-generate/blob/b56d7f3f0c4e9a2a8c50023baa290a494191a0d5/ucd-parse/src/error.rs#L29
- https://github.com/BurntSushi/fst/blob/715919a1bf658501f9028dbc5c3b7ebb5a508ea2/src/error.rs#L12
- https://github.com/BurntSushi/fst/blob/715919a1bf658501f9028dbc5c3b7ebb5a508ea2/src/raw/error.rs#L9