1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// SPDX-FileCopyrightText: 2025 RAprogramm <andrey.rozanov.vl@gmail.com>
//
// SPDX-License-Identifier: MIT
use alloc::{borrow::Cow, boxed::Box};
use core::error::Error as CoreError;
#[cfg(feature = "backtrace")]
use {alloc::sync::Arc, std::backtrace::Backtrace};
#[cfg(feature = "backtrace")]
use super::backtrace::capture_backtrace_snapshot;
use super::{
error::Error,
types::{CapturedBacktrace, ErrorChain}
};
use crate::app_error::metadata::Metadata;
impl Error {
/// Borrow the attached metadata.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, field};
///
/// let err = AppError::internal("test").with_field(field::str("key", "value"));
/// let metadata = err.metadata();
/// assert!(!metadata.is_empty());
/// ```
#[must_use]
pub fn metadata(&self) -> &Metadata {
&self.metadata
}
/// Borrow the backtrace, capturing it lazily when the `backtrace` feature
/// is enabled.
///
/// If a backtrace was previously attached via `with_backtrace()`, returns
/// that. Otherwise, lazily captures a new backtrace based on
/// `RUST_BACKTRACE` configuration.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "backtrace")]
/// # {
/// use masterror::AppError;
///
/// let err = AppError::internal("test");
/// let bt = err.backtrace();
/// # }
/// ```
#[must_use]
pub fn backtrace(&self) -> Option<&CapturedBacktrace> {
self.capture_backtrace()
}
/// Returns a shared Arc reference to the backtrace.
///
/// Internal method for efficient backtrace sharing between errors.
#[cfg(feature = "backtrace")]
pub(crate) fn backtrace_shared(&self) -> Option<Arc<Backtrace>> {
if let Some(backtrace) = self.backtrace.as_ref() {
return Some(Arc::clone(backtrace));
}
self.captured_backtrace
.get_or_init(capture_backtrace_snapshot)
.as_ref()
.map(Arc::clone)
}
/// Borrow the source if present.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use masterror::AppError;
///
/// let io_err = std::io::Error::new(std::io::ErrorKind::Other, "boom");
/// let err = AppError::internal("failed").with_context(io_err);
/// assert!(err.source_ref().is_some());
/// # }
/// ```
#[must_use]
pub fn source_ref(&self) -> Option<&(dyn CoreError + Send + Sync + 'static)> {
self.source.as_deref()
}
/// Human-readable message or the kind fallback.
///
/// Returns the error message if set, otherwise returns the error kind's
/// default label.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind};
///
/// let err = AppError::new(AppErrorKind::BadRequest, "custom message");
/// assert_eq!(err.render_message(), "custom message");
///
/// let bare_err = AppError::bare(AppErrorKind::NotFound);
/// assert!(!bare_err.render_message().is_empty());
/// ```
#[must_use]
pub fn render_message(&self) -> Cow<'_, str> {
match &self.message {
Some(msg) => Cow::Borrowed(msg.as_ref()),
None => Cow::Borrowed(self.kind.label())
}
}
/// Emit telemetry (`tracing` event, metrics counter, backtrace capture).
///
/// Downstream code can call this to guarantee telemetry after mutating the
/// error. It is automatically invoked by constructors and conversions.
///
/// # Examples
///
/// ```rust
/// use masterror::AppError;
///
/// let err = AppError::internal("test");
/// err.log();
/// ```
pub fn log(&self) {
self.emit_telemetry();
}
/// Returns an iterator over the error chain, starting with this error.
///
/// The iterator yields references to each error in the source chain,
/// walking through [`source()`](CoreError::source) until reaching the
/// root cause.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use std::io::Error as IoError;
///
/// use masterror::AppError;
///
/// let io_err = IoError::other("disk offline");
/// let app_err = AppError::internal("db down").with_context(io_err);
///
/// let chain: Vec<_> = app_err.chain().collect();
/// assert_eq!(chain.len(), 2);
/// # }
/// ```
#[must_use]
pub fn chain(&self) -> ErrorChain<'_> {
ErrorChain {
current: Some(self as &(dyn CoreError + 'static))
}
}
/// Returns the lowest-level source error in the chain.
///
/// This traverses the error source chain until it finds an error with no
/// further source, then returns a reference to it. If this error has no
/// source, it returns a reference to itself.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use std::io::Error as IoError;
///
/// use masterror::AppError;
///
/// let io_err = IoError::other("disk offline");
/// let app_err = AppError::internal("db down").with_context(io_err);
///
/// let root = app_err.root_cause();
/// assert_eq!(root.to_string(), "disk offline");
/// # }
/// ```
#[must_use]
pub fn root_cause(&self) -> &(dyn CoreError + 'static) {
self.chain()
.last()
.expect("chain always has at least one error")
}
/// Attempts to downcast the error source to a concrete type.
///
/// Returns `true` if the error source is of type `E`, `false` otherwise.
/// This only checks the immediate source, not the entire chain.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use std::io::Error as IoError;
///
/// use masterror::AppError;
///
/// let io_err = IoError::other("disk offline");
/// let app_err = AppError::internal("db down").with_context(io_err);
///
/// assert!(app_err.is::<IoError>());
///
/// let err_without_source = AppError::not_found("missing");
/// assert!(!err_without_source.is::<IoError>());
/// # }
/// ```
#[must_use]
pub fn is<E>(&self) -> bool
where
E: CoreError + 'static
{
self.source_ref().is_some_and(|source| source.is::<E>())
}
/// Attempt to downcast the error source to a concrete type by value.
///
/// **Note:** This method is currently a stub and always returns
/// `Err(Self)`.
///
/// Use [`downcast_ref`](Self::downcast_ref) for inspecting error sources.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use std::io::Error as IoError;
///
/// use masterror::AppError;
///
/// let io_err = IoError::other("disk offline");
/// let err = AppError::internal("boom").with_context(io_err);
///
/// assert!(err.downcast::<IoError>().is_err());
/// # }
/// ```
pub fn downcast<E>(self) -> Result<Box<E>, Self>
where
E: CoreError + 'static
{
Err(self)
}
/// Attempt to downcast the error to a concrete type by immutable
/// reference.
///
/// Returns `Some(&E)` if this error is of type `E`, `None` otherwise.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use std::io::Error as IoError;
///
/// use masterror::AppError;
///
/// let io_err = IoError::other("disk offline");
/// let err = AppError::internal("boom").with_context(io_err);
///
/// if let Some(io) = err.downcast_ref::<IoError>() {
/// assert_eq!(io.to_string(), "disk offline");
/// }
/// # }
/// ```
#[must_use]
pub fn downcast_ref<E>(&self) -> Option<&E>
where
E: CoreError + 'static
{
self.source_ref()?.downcast_ref::<E>()
}
/// Attempt to downcast the error to a concrete type by mutable reference.
///
/// Returns `Some(&mut E)` if this error is of type `E`, `None` otherwise.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use std::io::Error as IoError;
///
/// use masterror::AppError;
///
/// let io_err = IoError::other("disk offline");
/// let mut err = AppError::internal("boom").with_context(io_err);
///
/// if let Some(_io) = err.downcast_mut::<IoError>() {
/// // Can modify the IoError if needed
/// }
/// # }
/// ```
#[must_use]
pub fn downcast_mut<E>(&mut self) -> Option<&mut E>
where
E: CoreError + 'static
{
None
}
}