thiserror_string_context
This crate extends thiserror with possibility to add string context to error enums.
A typical usage is annotating io::Error
with a file name, but it can be used in any case where a string annotation of the error is required.
Relation to other similar crates
This crate is not as flexible in adding the context as anyhow or snafu, but instead it has a neglegible overhead and is much more ergonomic to use. It only serves a single purpose: adding an explanatory string to the error enum generated with thiserror
. It doesn't work for any error types other than enums and doesn't support any other context types than strings.
In contrast to the other crate with similar purpose - thiserror-context, this crate does not obliges the user to create two distinct error types with and without the context. Instead the hidded context variant is added to the error enum itself, which makes this solution more elegant and much easier to maintain.
Usage
The usage is very simple:
use Error;
use *;
// Annotate your error enum with `string_context` attribute.
// This will allow to use `MyError::with_context()` method
// to add a string annotation to your errors.
// You may add a custom error message where `{0}`
// is your original error variant.
This crashes with the following message:
Custom context message: Crashing with value 41
Caused by:
Slight underflow happened!
Matching on error enums with context
When the context is added to the error enum a hidden variant is added to it, which makes matching on enum variants somewhat tedious. The method unwrap_context
retuns a tuple where the first element is Option<String>
containing the context (if there is any) and the second is the enum itself "peeled" from the context. This allows very simple matching:
if let Err = initiate_error
License: MIT OR Apache-2.0