thiserror_string_context/lib.rs
1//! This crate extends [thiserror](https://crates.io/crates/thiserror/) with possibility to add string context to error enums.
2//!
3//! 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.
4//!
5//! # Relation to other similar crates
6//! This crate is not as flexible in adding the context as [anyhow](https://crates.io/crates/anyhow) or [snafu](https://crates.io/crates/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.
7//!
8//! In contrast to the other crate with similar purpose - [thiserror-context](https://crates.io/crates/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.
9//!
10//! # Usage
11//! The usage is very simple:
12//! ```should_panic
13//! use thiserror::Error;
14//! use thiserror_string_context::*;
15//!
16//! // Annotate your error enum with `string_context` attribute.
17//! // This will allow to use `MyError::with_context()` method
18//! // to add a string annotation to your errors.
19//! // You may add a custom error message where `{0}`
20//! // is your original error variant.
21//! #[string_context("Custom context message: {0}")]
22//! #[derive(Error,Debug)]
23//! enum MyError {
24//! #[error("Slight underflow happened!")]
25//! Underflow,
26//! #[error("slight overflow happened!")]
27//! Overflow,
28//! #[error("too far from correct!")]
29//! TooFar,
30//! }
31//!
32//! fn check_number(n: i32) -> Result<(),MyError> {
33//! match n {
34//! 42 => println!("Correct number!"),
35//! 41 => return Err(MyError::Underflow),
36//! 43 => return Err(MyError::Overflow),
37//! _ => return Err(MyError::TooFar),
38//! }
39//! Ok(())
40//! }
41//!
42//! fn initiate_error() -> anyhow::Result<()> {
43//! // Here we add a context message
44//! check_number(41).with_context(|| "Crashing with value 41")?;
45//! Ok(())
46//! }
47//!
48//! # fn main() {
49//! # initiate_error().unwrap();
50//! # }
51//! ```
52//! This crashes with the following message:
53//! ```text
54//! Custom context message: Crashing with value 41
55//!
56//! Caused by:
57//! Slight underflow happened!
58//! ```
59//!
60//! # Matching on error enums with context
61//! 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:
62//! ```ignore
63//! if let Err(err) = initiate_error() {
64//! // Run different actions on different error variants
65//! match err.unwrap_context() {
66//! // Different actions could be performed on the same
67//! // variant with and without the context
68//! (Some(ctx),MyError::Underflow) => {...},
69//! (None,MyError::Underflow) => {...},
70//! // The context could be ignored
71//! (_,MyError::Overflow) => {...},
72//! // The wildcard pattern is required
73//! _ => {...},
74//! }
75//! }
76//! ```
77
78pub use thiserror_string_context_macro::string_context;
79
80pub trait AddErrorContext<E,T,S> {
81 fn with_context(self, f: impl FnOnce()->S) -> std::result::Result<T, E>;
82}
83
84#[cfg(test)]
85mod tests {
86 use thiserror::Error;
87 use super::*;
88
89 #[string_context("Custom context messag: {0}")]
90 #[derive(Error,Debug)]
91 enum MyError {
92 #[error("Error 1")]
93 Error1,
94 #[error("Error 2")]
95 Error2,
96 #[error("Error 3")]
97 Error3,
98 }
99
100 fn callme(n: i32) -> Result<(),MyError> {
101 match n {
102 42 => println!("Nice number!"),
103 1 => return Err(MyError::Error1),
104 2 => return Err(MyError::Error2),
105 _ => return Err(MyError::Error3),
106 }
107 Ok(())
108 }
109
110 #[test]
111 #[should_panic]
112 fn test1() {
113 callme(42).unwrap();
114 callme(1).with_context(|| "Crashing with value 1").unwrap();
115 }
116
117
118}