error_kind/traits/error.rs
1// =============================================================================
2// USES
3// =============================================================================
4
5// -----------------------------------------------------------------------------
6use crate::{ErrorContext, ErrorKind};
7
8// =============================================================================
9// TRAITS
10// =============================================================================
11
12/// An error that contains an associated [`ErrorKind`].
13///
14/// Error types are expected to be fairly simple structs, usually containing
15/// only a single field.
16///
17/// ```
18/// use error_kind::{Error, ErrorKind};
19///
20/// #[derive(Clone, Copy, Debug, ErrorKind)]
21/// enum MyErrorKind {
22/// Variant,
23/// }
24///
25/// #[derive(Debug, Error)]
26/// struct MyError(MyErrorKind);
27/// ```
28///
29/// If you plan on having many different kinds of errors within a crate, you may
30/// wish to make your type generic over the kind of error.
31///
32/// ```
33/// use error_kind::{Error, ErrorKind};
34///
35/// #[derive(Debug, Error)]
36/// struct MyError<K: ErrorKind>(K);
37/// ```
38///
39/// Your error kind can also be wrapped in [`envelopes`] to collect additional
40/// error information.
41///
42/// [`envelopes`]: crate::envelopes
43///
44/// # Traits Implemented
45///
46/// The derive macro helps us out a lot here, implementing the following traits:
47///
48/// - [`Display`]
49/// - [`ErrorContext`]
50/// - [`Error`] (both `core` and `error_kind`)
51/// - [`From`] (via `#[error(domains(...))]`)
52/// - [`TrivialError`]
53///
54/// [`Display`]: core::fmt::Display
55/// [`TrivialError`]: crate::TrivialError
56///
57/// You can disable any of these by using the `#[error(disable(...))]` attribute
58/// (e.g. `#[error(disable(From, Display))]`).
59///
60/// You can force-hide certain trait implementations from documentation by using
61/// the `#[error(hidden(...))]` attribute (e.g.
62/// `#[error(hidden(TrivialError))]`).
63///
64/// ```rust
65/// # use error_kind::{Error, ErrorKind};
66/// # #[derive(Clone, Copy, Debug, ErrorKind)]
67/// # enum MyErrorKind { Variant }
68///
69/// #[derive(Debug, Error)]
70/// #[error(disable(Display, TrivialError))]
71/// #[error(hidden(core::error::Error))]
72/// struct NoDisplayExample(MyErrorKind);
73///
74/// // Though, now you have to implement `Display` yourself.
75/// // This is required since `Display` is a supertrait of `Error`.
76/// impl std::fmt::Display for NoDisplayExample {
77/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
78/// # unimplemented!()
79/// // ...
80/// }
81/// }
82/// ```
83///
84/// # Error Domains
85///
86/// If your crate defines any [`ErrorDomain`]s that you would like your error to
87/// be able to convert between, register them with `#[error(domains(...))]`.
88///
89/// [`ErrorDomain`]: crate::ErrorDomain
90///
91/// **This allows for...**
92///
93/// - Conversion from `MyError<MyErrorKind>` to `MyError<_>` for any
94/// registered [`ErrorDomain`] which contains `MyErrorKind`.
95/// - Conversion from `MyError<MyErrorDomain>` to `MyError<_>` for any
96/// registered [`ErrorDomain`] which contains a superset of all [`ErrorKind`]s
97/// present in `MyErrorDomain`.
98///
99/// ```rust
100/// # use error_kind::{Error, ErrorDomain, ErrorKind};
101/// # #[derive(Clone, Copy, Debug, ErrorKind, PartialEq)]
102/// # enum MyErrorKind1 { Variant }
103/// # #[derive(Clone, Copy, Debug, ErrorKind, PartialEq)]
104/// # enum MyErrorKind2 { Variant }
105/// # #[derive(Clone, Copy, Debug, ErrorKind, PartialEq)]
106/// # enum MyErrorKind3 { Variant }
107/// #[derive(Clone, Copy, Debug, ErrorDomain, PartialEq)]
108/// enum MyErrorDomain1 {
109/// Kind1(MyErrorKind1),
110/// Kind2(MyErrorKind2),
111/// // ...
112/// }
113///
114/// #[derive(Clone, Copy, Debug, ErrorDomain, PartialEq)]
115/// #[error(domains(MyErrorDomain1))] // <- Suggest a subset domain
116/// enum MyErrorDomain2 {
117/// Kind1(MyErrorKind1),
118/// Kind2(MyErrorKind2),
119/// Kind3(MyErrorKind3),
120/// // ...
121/// }
122///
123/// #[derive(Debug, Error, Eq, PartialEq)]
124/// #[error(domains(MyErrorDomain1, MyErrorDomain2))] // Because of this...
125/// struct MyError<K: ErrorKind>(K);
126///
127/// // ... these conversions work as expected!
128/// assert_eq!(
129/// MyError(MyErrorDomain1::Kind1(MyErrorKind1::Variant)),
130/// From::from(MyError(MyErrorKind1::Variant)),
131/// );
132/// assert_eq!(
133/// MyError(MyErrorDomain2::Kind1(MyErrorKind1::Variant)),
134/// From::from(MyError(MyErrorKind1::Variant)),
135/// );
136///
137/// // ... and perhaps surprisingly, this also works!
138/// assert_eq!(
139/// MyError(MyErrorDomain2::Kind1(MyErrorKind1::Variant)),
140/// From::from(MyError(MyErrorDomain1::Kind1(MyErrorKind1::Variant))),
141/// );
142/// ```
143///
144/// > **Learn More:** While you don't need to understand how this works, if you
145/// > are curious to learn, see the [`IsNot`] and [`MatchInto`] traits.
146///
147/// [`IsNot`]: crate::details::IsNot
148/// [`MatchInto`]: crate::details::MatchInto
149///
150/// # Trivial Errors
151///
152/// The [`TrivialError`] trait is used to power the [`err!`] macro.
153///
154/// If the error type only contains one field (the error kind), it's said to be
155/// trivial. In these cases, we can easily say how to properly construct it!
156///
157/// ```
158/// use error_kind::{Error, ErrorKind, TrivialError};
159///
160/// #[derive(Clone, Copy, Debug, ErrorKind)]
161/// enum MyErrorKind {
162/// Variant,
163/// }
164///
165/// #[derive(Debug, Error)]
166/// struct MyError(MyErrorKind);
167///
168/// // Allowed via the `TrivialError` trait.
169/// let _ = MyError::new(MyErrorKind::Variant);
170/// ```
171///
172/// However, if more than one field is present, the derive macro is not certain
173/// that taking the `Default` for the other values is the right thing to do.
174///
175/// As such, it will simply avoid implementing this trait.
176///
177/// ```compile_fail
178/// use error_kind::{Error, ErrorKind, TrivialError};
179///
180/// #[derive(Clone, Copy, Debug, ErrorKind)]
181/// enum MyErrorKind {
182/// Variant,
183/// }
184///
185/// #[derive(Debug, Error)]
186/// struct MyError(#[error_kind]MyErrorKind, u32);
187///
188/// // Not allowed, because of multiple fields. :(
189/// let _ = MyError::new(MyErrorKind::Variant);
190/// ```
191///
192/// In those cases, if you know better, you can implement [`TrivialError`]
193/// manually.
194///
195/// [`err!`]: crate::err
196///
197/// # Recommendation: Provide an `error_kind` Function
198///
199/// Though users can depend on this trait to acquire the underlying error kind,
200/// it's more ergonomic to simply provide a function on the error type itself.
201///
202/// **The `Error` derive macro *will not* implement this for you!**
203///
204/// ```
205/// use error_kind::{Error, ErrorKind};
206///
207/// #[derive(Copy, Clone, Debug, ErrorKind)]
208/// pub enum MyErrorKind {
209/// Error1,
210/// }
211///
212/// #[derive(Debug, Error)]
213/// pub struct MyError {
214/// error_kind: MyErrorKind,
215/// }
216///
217/// impl MyError {
218/// // We have to implement this manually, if we want it.
219/// pub fn error_kind(&self) -> MyErrorKind {
220/// self.error_kind
221/// }
222/// }
223/// ```
224///
225/// # Examples
226///
227/// This type supports named and unnamed type constructions.
228///
229/// ```rust
230/// # use error_kind::{Error, ErrorKind};
231/// # #[derive(Clone, Copy, Debug, ErrorKind)]
232/// # enum MyErrorKind { Variant }
233/// #[derive(Debug, Error)]
234/// struct NamedExample {
235/// error_kind: MyErrorKind,
236/// }
237///
238/// #[derive(Debug, Error)]
239/// struct UnnamedExample(MyErrorKind);
240/// ```
241///
242/// If multiple fields are present, one field must be marked as the field which
243/// contains our `ErrorKind` (using `#[error_kind]`).
244///
245/// ```rust
246/// # use error_kind::{Error, ErrorKind};
247/// # #[derive(Clone, Copy, Debug, ErrorKind)]
248/// # enum MyErrorKind { Variant }
249/// #[derive(Debug, Error)]
250/// struct MyError(u32, #[error_kind]MyErrorKind, i16);
251/// ```
252///
253/// Your error type is allowed to be generic over the `ErrorKind`. It's highly
254/// recommended that you add a bounds to the type parameter, however.
255///
256/// ```rust
257/// # use error_kind::{Error, ErrorKind};
258/// # #[derive(Clone, Copy, Debug, ErrorKind)]
259/// # enum MyErrorKind { Variant }
260/// #[derive(Debug, Error)]
261/// struct MyError<K: ErrorKind> {
262/// field_a: u32,
263/// #[error_kind]
264/// field_b: K,
265/// field_c: i16,
266/// }
267/// ```
268pub trait Error: core::error::Error + ErrorContext {
269 /// The `ErrorKind` that this error contains.
270 type Kind: ErrorKind;
271
272 /// Returns the `ErrorKind` contained within this error.
273 fn error_kind(&self) -> Self::Kind;
274}