atomic_circuit_breaker/error/impl.rs
1use super::*;
2
3/// Formats `CircuitBreakerError` variants as human-readable descriptions.
4impl fmt::Display for CircuitBreakerError {
5 /// Writes the error description to the formatter.
6 ///
7 /// # Arguments
8 ///
9 /// - `&Self` - The error variant.
10 /// - `&mut fmt::Formatter<'_>` - The target formatter.
11 ///
12 /// # Returns
13 ///
14 /// - `fmt::Result` - Result of formatting.
15 #[inline(always)]
16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17 match self {
18 Self::NoTripCondition => f.write_str(ERR_NO_TRIP_CONDITION),
19 Self::InvalidThreshold => f.write_str(ERR_INVALID_THRESHOLD),
20 Self::InvalidFailureRate => f.write_str(ERR_INVALID_FAILURE_RATE),
21 Self::ZeroWindow => f.write_str(ERR_ZERO_WINDOW),
22 Self::ZeroCooldown => f.write_str(ERR_ZERO_COOLDOWN),
23 Self::InvalidHalfOpenConfig => f.write_str(ERR_INVALID_HALF_OPEN),
24 Self::DurationOverflow => f.write_str(ERR_DURATION_OVERFLOW),
25 }
26 }
27}
28
29/// Marks `CircuitBreakerError` as a standard error type.
30impl Error for CircuitBreakerError {}
31
32/// Convenience predicates for `CallError`.
33impl<E> CallError<E> {
34 /// Returns `true` when the call was rejected by the circuit breaker without running.
35 ///
36 /// # Arguments
37 ///
38 /// - `&Self` - The call error.
39 ///
40 /// # Returns
41 ///
42 /// - `bool` - `true` for `CallError::Rejected`.
43 #[inline(always)]
44 pub fn is_rejected(&self) -> bool {
45 matches!(self, Self::Rejected { .. })
46 }
47
48 /// Consumes the error and returns the inner error if the operation ran and failed.
49 ///
50 /// # Arguments
51 ///
52 /// - `Self` - The call error.
53 ///
54 /// # Returns
55 ///
56 /// - `Option<E>` - `Some(inner)` for `CallError::Inner`, `None` for `Rejected`.
57 #[inline(always)]
58 pub fn into_inner(self) -> Option<E> {
59 match self {
60 Self::Inner(err) => Some(err),
61 Self::Rejected { .. } => None,
62 }
63 }
64}
65
66/// Formats `CallError` for diagnostics.
67impl<E> fmt::Display for CallError<E>
68where
69 E: fmt::Display,
70{
71 /// Writes a human-readable summary of the call error.
72 ///
73 /// # Arguments
74 ///
75 /// - `&Self` - The call error.
76 /// - `&mut fmt::Formatter<'_>` - The target formatter.
77 ///
78 /// # Returns
79 ///
80 /// - `fmt::Result` - Result of formatting.
81 #[inline(always)]
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 match self {
84 Self::Rejected {
85 state,
86 retry_after_ns,
87 } => write!(
88 f,
89 "{ERR_CALL_REJECTED} (state={state}, retry_after_ns={retry_after_ns})"
90 ),
91 Self::Inner(err) => fmt::Display::fmt(err, f),
92 }
93 }
94}
95
96/// Marks `CallError<E>` as a standard error when `E` implements `Error`.
97impl<E> Error for CallError<E> where E: Error + 'static {}