@@ -18,6 +18,76 @@ use types::ErrorStackDeriveInput;
1818
1919mod util;
2020
21+ /// Derive macro for the [`Error`] trait that implements the best practices for
22+ /// [`error-stack`].
23+ ///
24+ /// # Overview
25+ /// This derive macro allows you to automatically implement the required
26+ /// [`Display`] and [`Error`] traits for custom types that you want to use as
27+ /// context types in [`error-stack`] [`Report`]s without all the boilerplate.
28+ ///
29+ /// The macro has a `display` attribute, which specifies a formatting string to
30+ /// print a value of the given type or enum variant.
31+ ///
32+ /// # Examples
33+ ///
34+ /// ## Unit struct (recommended)
35+ ///
36+ /// ```
37+ /// use error_stack_macros2::Error;
38+ ///
39+ /// #[derive(Debug, Error)]
40+ /// #[display("invalid card string")]
41+ /// struct ParseCardError;
42+ /// ```
43+ ///
44+ /// ## Enum
45+ ///
46+ /// ```
47+ /// use error_stack_macros2::Error;
48+ ///
49+ /// #[derive(Debug, Error)]
50+ /// #[display("credit card error")] // optional default
51+ /// enum CreditCardError {
52+ /// #[display("credit card not found")]
53+ /// InvalidInput(String),
54+ ///
55+ /// #[display("failed to retrieve credit card")]
56+ /// Other,
57+ /// }
58+ /// ```
59+ ///
60+ /// ## Field interpolation (discouraged)
61+ ///
62+ /// ```
63+ /// use error_stack_macros2::Error;
64+ ///
65+ /// #[derive(Debug, Error)]
66+ /// #[display("invalid card string: {0:?}")]
67+ /// struct ParseCardError(String);
68+ ///
69+ /// let err = ParseCardError("1234567".to_string());
70+ /// assert_eq!(err.to_string(), "invalid card string: \"1234567\"");
71+ /// ```
72+ ///
73+ /// # This may look familiar...
74+ ///
75+ /// This derive macro is heavily inspired by the popular [`thiserror`] crate. In
76+ /// fact, you **can** use the [`thiserror`] crate to derive the same traits for
77+ /// your types. However, [`error-stack`] is very opinionated about how context
78+ /// types should be designed and used, and this derive macro enforces those
79+ /// best practices, whereas [`thiserror`] is more flexible and designed for
80+ /// general use cases.
81+ ///
82+ /// Also, due to this macro's more simple and restricted design, it can
83+ /// potentially be more efficient than [`thiserror`] in terms of compile time
84+ /// and generated code size.
85+ ///
86+ /// [`Error`]: core::error::Error
87+ /// [`error-stack`]: https://crates.io/crates/error-stack
88+ /// [`Report`]: https://docs.rs/error-stack/latest/error_stack/struct.Report.html
89+ /// [`Display`]: core::fmt::Display
90+ /// [`thiserror`]: https://crates.io/crates/thiserror
2191#[ proc_macro_derive( Error , attributes( display) ) ]
2292pub fn impl_error_stack ( input : TokenStream ) -> TokenStream {
2393 let derive_input = parse_macro_input ! ( input as ErrorStackDeriveInput ) ;
0 commit comments