error_kind/traits/error_context.rs
1// =============================================================================
2// USES
3// =============================================================================
4
5// -----------------------------------------------------------------------------
6use crate::Context;
7
8// =============================================================================
9// TYPES
10// =============================================================================
11
12/// Propose additional error context for the error to consider collecting.
13///
14/// The information provided to `ErrorContext` should be thought of as debugging
15/// information *only*. You should never depend on any of this information
16/// logically.
17///
18/// Whether or not this context information is collected depends on how you
19/// define your [`Error`] type.
20///
21/// [`Error`]: crate::Error
22pub trait ErrorContext {
23 /// Provide human-readable context about why an error occurred.
24 ///
25 /// Context is collected if the error supports it with the proper
26 /// [`envelopes`]. If collected, it will be printed in stack order (first
27 /// piece of context added prints first, followed by the next, etc).
28 ///
29 /// [`envelopes`]: crate::envelopes
30 fn with_context<C, F>(self, context: F) -> Self
31 where
32 C: Context,
33 F: FnOnce() -> C;
34}
35
36// =============================================================================
37// TRAIT IMPLS
38// =============================================================================
39
40// -----------------------------------------------------------------------------
41impl<T: ErrorContext> ErrorContext for Option<T> {
42 #[allow(clippy::manual_map)] // Messes with #[track_caller]
43 #[track_caller]
44 #[inline]
45 fn with_context<C, F>(self, context: F) -> Self
46 where
47 C: Context,
48 F: FnOnce() -> C,
49 {
50 match self {
51 None => None,
52 Some(err) => Some(err.with_context(context)),
53 }
54 }
55}
56
57// -----------------------------------------------------------------------------
58impl<T, E: ErrorContext> ErrorContext for Result<T, E> {
59 #[allow(clippy::manual_map)] // Messes with #[track_caller]
60 #[track_caller]
61 #[inline]
62 fn with_context<C, F>(self, context: F) -> Self
63 where
64 C: Context,
65 F: FnOnce() -> C,
66 {
67 match self {
68 Ok(val) => Ok(val),
69 Err(err) => Err(err.with_context(context)),
70 }
71 }
72}