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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// SPDX-FileCopyrightText: 2025 RAprogramm <andrey.rozanov.vl@gmail.com>
//
// SPDX-License-Identifier: MIT
use alloc::{borrow::Cow, string::String, sync::Arc};
use core::error::Error as CoreError;
#[cfg(feature = "backtrace")]
use std::backtrace::Backtrace;
#[cfg(feature = "serde_json")]
use serde::Serialize;
#[cfg(feature = "serde_json")]
use serde_json::{Value as JsonValue, to_value};
use super::{
error::Error,
types::{CapturedBacktrace, ContextAttachment, MessageEditPolicy}
};
use crate::{
AppCode, AppErrorKind, RetryAdvice,
app_error::metadata::{Field, FieldRedaction, Metadata}
};
impl Error {
/// Create a new [`Error`] with a kind and message.
///
/// This is equivalent to [`Error::with`], provided for API symmetry and to
/// keep doctests readable.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind};
/// let err = AppError::new(AppErrorKind::BadRequest, "invalid payload");
/// assert!(err.message.is_some());
/// ```
#[must_use]
pub fn new(kind: AppErrorKind, msg: impl Into<Cow<'static, str>>) -> Self {
Self::with(kind, msg)
}
/// Create an error with the given kind and message.
///
/// Prefer named helpers (e.g. [`Error::not_found`]) where it clarifies
/// intent.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind};
/// let err = AppError::with(AppErrorKind::Validation, "bad input");
/// assert_eq!(err.kind, AppErrorKind::Validation);
/// ```
#[must_use]
pub fn with(kind: AppErrorKind, msg: impl Into<Cow<'static, str>>) -> Self {
let err = Self::new_raw(kind, Some(msg.into()));
err.emit_telemetry();
err
}
/// Create a message-less error with the given kind.
///
/// Useful when the kind alone conveys sufficient information to the client.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind};
/// let err = AppError::bare(AppErrorKind::NotFound);
/// assert!(err.message.is_none());
/// ```
#[must_use]
pub fn bare(kind: AppErrorKind) -> Self {
let err = Self::new_raw(kind, None);
err.emit_telemetry();
err
}
/// Override the machine-readable [`AppCode`].
///
/// # Examples
///
/// ```rust
/// use masterror::{AppCode, AppError, AppErrorKind};
/// let err = AppError::new(AppErrorKind::BadRequest, "test").with_code(AppCode::NotFound);
/// assert_eq!(err.code, AppCode::NotFound);
/// ```
#[must_use]
pub fn with_code(mut self, code: AppCode) -> Self {
self.code = code;
self.mark_dirty();
self
}
/// Attach retry advice to the error.
///
/// When mapped to HTTP, this becomes the `Retry-After` header.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind};
/// let err = AppError::new(AppErrorKind::RateLimited, "slow down").with_retry_after_secs(60);
/// assert_eq!(err.retry.map(|r| r.after_seconds), Some(60));
/// ```
#[must_use]
pub fn with_retry_after_secs(mut self, secs: u64) -> Self {
self.retry = Some(RetryAdvice {
after_seconds: secs
});
self.mark_dirty();
self
}
/// Attach a `WWW-Authenticate` challenge string.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind};
/// let err = AppError::new(AppErrorKind::Unauthorized, "auth required")
/// .with_www_authenticate("Bearer realm=\"api\"");
/// assert!(err.www_authenticate.is_some());
/// ```
#[must_use]
pub fn with_www_authenticate(mut self, value: impl Into<String>) -> Self {
self.www_authenticate = Some(value.into());
self.mark_dirty();
self
}
/// Attach additional metadata to the error.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind, field};
/// let err = AppError::new(AppErrorKind::Validation, "bad field")
/// .with_field(field::str("field_name", "email"));
/// assert!(err.metadata().get("field_name").is_some());
/// ```
#[must_use]
pub fn with_field(mut self, field: Field) -> Self {
self.metadata.insert(field);
self.mark_dirty();
self
}
/// Extend metadata from an iterator of fields.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind, field};
/// let fields = vec![field::str("key1", "value1"), field::str("key2", "value2")];
/// let err = AppError::new(AppErrorKind::BadRequest, "test").with_fields(fields);
/// assert!(err.metadata().get("key1").is_some());
/// ```
#[must_use]
pub fn with_fields(mut self, fields: impl IntoIterator<Item = Field>) -> Self {
self.metadata.extend(fields);
self.mark_dirty();
self
}
/// Override the redaction policy for a stored metadata field.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind, FieldRedaction, field};
///
/// let err = AppError::new(AppErrorKind::Internal, "test")
/// .with_field(field::str("password", "secret"))
/// .redact_field("password", FieldRedaction::Redact);
/// ```
#[must_use]
pub fn redact_field(mut self, name: &'static str, redaction: FieldRedaction) -> Self {
self.metadata.set_redaction(name, redaction);
self.mark_dirty();
self
}
/// Replace metadata entirely.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind, Metadata};
///
/// let metadata = Metadata::new();
/// let err = AppError::new(AppErrorKind::Internal, "test").with_metadata(metadata);
/// ```
#[must_use]
pub fn with_metadata(mut self, metadata: Metadata) -> Self {
self.metadata = metadata;
self.mark_dirty();
self
}
/// Mark the message as redactable.
///
/// # Examples
///
/// ```rust
/// use masterror::{AppError, AppErrorKind, MessageEditPolicy};
///
/// let err = AppError::new(AppErrorKind::Internal, "secret").redactable();
/// assert_eq!(err.edit_policy, MessageEditPolicy::Redact);
/// ```
#[must_use]
pub fn redactable(mut self) -> Self {
self.edit_policy = MessageEditPolicy::Redact;
self.mark_dirty();
self
}
/// Attach upstream diagnostics using [`with_source`](Self::with_source) or
/// an existing [`Arc`].
///
/// This is the preferred alias for capturing upstream errors. It accepts
/// either an owned error implementing [`core::error::Error`] or a
/// shared [`Arc`] produced by other APIs, reusing the allocation when
/// possible.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use masterror::AppError;
///
/// let err = AppError::service("downstream degraded")
/// .with_context(std::io::Error::new(std::io::ErrorKind::Other, "boom"));
/// assert!(err.source_ref().is_some());
/// # }
/// ```
#[must_use]
pub fn with_context(self, context: impl Into<ContextAttachment>) -> Self {
match context.into() {
ContextAttachment::Owned(source) => {
match source.downcast::<Arc<dyn CoreError + Send + Sync + 'static>>() {
Ok(shared) => self.with_source_arc(*shared),
Err(source) => self.with_source_arc(Arc::from(source))
}
}
ContextAttachment::Shared(source) => self.with_source_arc(source)
}
}
/// Attach a source error for diagnostics.
///
/// Prefer [`with_context`](Self::with_context) when capturing upstream
/// diagnostics without additional `Arc` allocations.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use masterror::{AppError, AppErrorKind};
///
/// let io_err = std::io::Error::new(std::io::ErrorKind::Other, "boom");
/// let err = AppError::internal("boom").with_source(io_err);
/// assert!(err.source_ref().is_some());
/// # }
/// ```
#[must_use]
pub fn with_source(mut self, source: impl CoreError + Send + Sync + 'static) -> Self {
self.source = Some(Arc::new(source));
self.mark_dirty();
self
}
/// Attach a shared source error without cloning the underlying `Arc`.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "std")] {
/// use std::sync::Arc;
///
/// use masterror::{AppError, AppErrorKind};
///
/// let source = Arc::new(std::io::Error::new(std::io::ErrorKind::Other, "boom"));
/// let err = AppError::internal("boom").with_source_arc(source.clone());
/// assert!(err.source_ref().is_some());
/// assert_eq!(Arc::strong_count(&source), 2);
/// # }
/// ```
#[must_use]
pub fn with_source_arc(mut self, source: Arc<dyn CoreError + Send + Sync + 'static>) -> Self {
self.source = Some(source);
self.mark_dirty();
self
}
/// Attach a captured backtrace.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "backtrace")]
/// # {
/// use std::backtrace::Backtrace;
///
/// use masterror::AppError;
///
/// let bt = Backtrace::capture();
/// let err = AppError::internal("test").with_backtrace(bt);
/// # }
/// ```
#[must_use]
pub fn with_backtrace(mut self, backtrace: CapturedBacktrace) -> Self {
#[cfg(feature = "backtrace")]
{
self.set_backtrace_slot(Arc::new(backtrace));
}
#[cfg(not(feature = "backtrace"))]
{
self.set_backtrace_slot(backtrace);
}
self.mark_dirty();
self
}
/// Attach a shared backtrace without cloning.
///
/// Internal method for sharing backtraces between errors.
#[cfg(feature = "backtrace")]
pub(crate) fn with_shared_backtrace(mut self, backtrace: Arc<Backtrace>) -> Self {
self.set_backtrace_slot(backtrace);
self.mark_dirty();
self
}
/// Attach structured JSON details for the client payload.
///
/// The details are omitted from responses when the error has been marked as
/// [`redactable`](Self::redactable).
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "serde_json")]
/// # {
/// use masterror::{AppError, AppErrorKind};
/// use serde_json::json;
///
/// let err = AppError::new(AppErrorKind::Validation, "invalid input")
/// .with_details_json(json!({"field": "email"}));
/// assert!(err.details.is_some());
/// # }
/// ```
#[must_use]
#[cfg(feature = "serde_json")]
pub fn with_details_json(mut self, details: JsonValue) -> Self {
self.details = Some(details);
self.mark_dirty();
self
}
/// Serialize and attach structured details.
///
/// Returns [`crate::AppError`] with [`crate::AppErrorKind::BadRequest`] if
/// serialization fails.
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "serde_json")]
/// # {
/// use masterror::{AppError, AppErrorKind};
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Extra {
/// reason: &'static str
/// }
///
/// let err = AppError::new(AppErrorKind::BadRequest, "invalid")
/// .with_details(Extra {
/// reason: "missing"
/// })
/// .expect("details should serialize");
/// assert!(err.details.is_some());
/// # }
/// ```
#[cfg(feature = "serde_json")]
#[allow(clippy::result_large_err)]
pub fn with_details<T>(self, payload: T) -> crate::AppResult<Self>
where
T: Serialize
{
let details = to_value(payload).map_err(|err| Self::bad_request(err.to_string()))?;
Ok(self.with_details_json(details))
}
/// Attach plain-text details for client payloads.
///
/// The text is omitted from responses when the error is
/// [`redactable`](Self::redactable).
///
/// # Examples
///
/// ```rust
/// # #[cfg(not(feature = "serde_json"))]
/// # {
/// use masterror::{AppError, AppErrorKind};
///
/// let err = AppError::new(AppErrorKind::Internal, "boom").with_details_text("retry later");
/// assert!(err.details.is_some());
/// # }
/// ```
#[must_use]
#[cfg(not(feature = "serde_json"))]
pub fn with_details_text(mut self, details: impl Into<String>) -> Self {
self.details = Some(details.into());
self.mark_dirty();
self
}
}