masterror 0.29.0

Application error types and response mapping
Documentation
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
421
422
423
424
425
426
427
// SPDX-FileCopyrightText: 2025 RAprogramm <andrey.rozanov.vl@gmail.com>
//
// SPDX-License-Identifier: MIT

/// Backtrace capture and configuration.
///
/// Provides backtrace capture functionality with environment-based
/// configuration via `RUST_BACKTRACE`. Handles lazy capture and caching
/// for optimal performance.
#[cfg(feature = "backtrace")]
pub mod backtrace;

/// Builder methods for error construction and mutation.
///
/// Provides fluent API for constructing errors with various properties:
/// - Message and code configuration
/// - Metadata attachment
/// - Source error chaining
/// - Retry advice and authentication challenges
/// - Structured details (JSON or text)
pub mod builder;

/// Core error types and internal representation.
///
/// Defines the main `Error` type and its internal state structure.
/// Provides the foundation for all error handling in the library.
pub mod error;

/// Error introspection and diagnostic methods.
///
/// Provides methods for examining error properties:
/// - Chain traversal
/// - Source inspection
/// - Type downcasting
/// - Message rendering
/// - Metadata access
pub mod introspection;

/// Telemetry integration (metrics and tracing).
///
/// Handles emission of metrics and tracing events when errors are created
/// or modified. Supports conditional compilation for different telemetry
/// backends.
pub mod telemetry;

/// Helper types and utilities.
///
/// Provides supporting types used throughout the error system:
/// - `ContextAttachment` for source error attachment
/// - `MessageEditPolicy` for redaction control
/// - `ErrorChain` iterator for chain traversal
/// - `CapturedBacktrace` type alias
pub mod types;

/// Environment detection and mode-aware `Display` layouts.
///
/// Provides [`DisplayMode`], which detects the deployment environment from
/// `MASTERROR_ENV`, `KUBERNETES_SERVICE_HOST` or build configuration and
/// caches the result once per process. The `Display` implementation for
/// `Error` dispatches on this mode: `Local` renders a multi-line
/// human-readable report, while `Prod` and `Staging` render compact JSON
/// with redaction-aware metadata.
pub mod display;

#[cfg(all(test, feature = "backtrace"))]
pub use backtrace::{reset_backtrace_preference, set_backtrace_preference_override};
pub use display::DisplayMode;
pub use error::{AppError, AppResult, Error};
pub use types::{ErrorChain, MessageEditPolicy};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::AppErrorKind;

    #[test]
    fn error_new_creates_error_with_message() {
        let err = Error::new(AppErrorKind::BadRequest, "invalid input");
        assert_eq!(err.kind, AppErrorKind::BadRequest);
        assert_eq!(err.message.as_deref(), Some("invalid input"));
    }

    #[test]
    fn error_with_creates_error_with_message() {
        let err = Error::with(AppErrorKind::NotFound, "not found");
        assert_eq!(err.kind, AppErrorKind::NotFound);
        assert_eq!(err.message.as_deref(), Some("not found"));
    }

    #[test]
    fn error_bare_creates_error_without_message() {
        let err = Error::bare(AppErrorKind::Internal);
        assert_eq!(err.kind, AppErrorKind::Internal);
        assert!(err.message.is_none());
    }

    #[test]
    fn error_with_code_overrides_code() {
        use crate::AppCode;
        let err = Error::new(AppErrorKind::BadRequest, "test").with_code(AppCode::NotFound);
        assert_eq!(err.code, AppCode::NotFound);
    }

    #[test]
    fn error_with_retry_after_secs_sets_retry() {
        let err = Error::new(AppErrorKind::RateLimited, "slow down").with_retry_after_secs(60);
        assert_eq!(err.retry.map(|r| r.after_seconds), Some(60));
    }

    #[test]
    fn error_with_www_authenticate_sets_header() {
        let err = Error::new(AppErrorKind::Unauthorized, "auth required")
            .with_www_authenticate("Bearer realm=\"api\"");
        assert_eq!(
            err.www_authenticate.as_deref(),
            Some("Bearer realm=\"api\"")
        );
    }

    #[test]
    fn error_with_field_adds_metadata() {
        use crate::field;
        let err = Error::new(AppErrorKind::Validation, "bad field")
            .with_field(field::str("field_name", "email"));
        assert_eq!(
            err.metadata().get("field_name"),
            Some(&crate::app_error::metadata::FieldValue::Str("email".into()))
        );
    }

    #[test]
    fn error_with_fields_adds_multiple_metadata() {
        use crate::field;
        let fields = vec![field::str("key1", "value1"), field::str("key2", "value2")];
        let err = Error::new(AppErrorKind::BadRequest, "test").with_fields(fields);
        assert!(err.metadata().get("key1").is_some());
        assert!(err.metadata().get("key2").is_some());
    }

    #[test]
    fn error_redactable_sets_edit_policy() {
        let err = Error::new(AppErrorKind::Internal, "secret").redactable();
        assert_eq!(err.edit_policy, MessageEditPolicy::Redact);
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_with_source_attaches_source() {
        use std::io::Error as IoError;
        let io_err = IoError::other("disk error");
        let err = Error::new(AppErrorKind::Internal, "fail").with_source(io_err);
        assert!(err.source_ref().is_some());
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_with_context_attaches_source() {
        use std::io::Error as IoError;
        let io_err = IoError::other("network error");
        let err = Error::new(AppErrorKind::Network, "fail").with_context(io_err);
        assert!(err.source_ref().is_some());
    }

    #[test]
    fn error_metadata_returns_metadata() {
        use crate::field;
        let err =
            Error::new(AppErrorKind::Internal, "test").with_field(field::str("test", "value"));
        let metadata = err.metadata();
        assert!(!metadata.is_empty());
    }

    #[test]
    fn error_render_message_returns_message_when_present() {
        let err = Error::new(AppErrorKind::BadRequest, "custom message");
        assert_eq!(err.render_message(), "custom message");
    }

    #[test]
    fn error_render_message_returns_kind_label_when_no_message() {
        let err = Error::bare(AppErrorKind::NotFound);
        assert!(!err.render_message().is_empty());
    }

    #[test]
    fn error_display_shows_kind() {
        let _guard = display::force_display_mode(DisplayMode::Local);
        let err = Error::new(AppErrorKind::Internal, "test");
        let display = format!("{}", err);
        assert!(display.contains("Error: Internal server error"));
        assert!(display.contains("Code: INTERNAL"));
        assert!(display.contains("Message: test"));
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_chain_returns_iterator() {
        use std::io::Error as IoError;
        let io_err = IoError::other("root cause");
        let err = Error::new(AppErrorKind::Internal, "wrapper").with_context(io_err);
        let chain: Vec<_> = err.chain().collect();
        assert_eq!(chain.len(), 2);
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_root_cause_returns_lowest_error() {
        use std::io::Error as IoError;
        let io_err = IoError::other("disk offline");
        let err = Error::new(AppErrorKind::Internal, "db down").with_context(io_err);
        let root = err.root_cause();
        assert_eq!(root.to_string(), "disk offline");
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_is_checks_source_type() {
        use std::io::Error as IoError;
        let io_err = IoError::other("test");
        let err = Error::new(AppErrorKind::Network, "fail").with_context(io_err);
        assert!(err.is::<IoError>());
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_ref_returns_concrete_type() {
        use std::io::Error as IoError;
        let io_err = IoError::other("disk error");
        let err = Error::new(AppErrorKind::Internal, "fail").with_context(io_err);
        assert!(err.downcast_ref::<IoError>().is_some());
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_mut_returns_source_for_owned_source() {
        use std::io::Error as IoError;
        let io_err = IoError::other("test");
        let mut err = Error::new(AppErrorKind::Internal, "fail").with_context(io_err);
        let source = err.downcast_mut::<IoError>().expect("owned io source");
        assert_eq!(source.to_string(), "test");
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_mut_mutation_visible_via_downcast_ref() {
        use std::io::Error as IoError;
        let io_err = IoError::other("before");
        let mut err = Error::new(AppErrorKind::Internal, "fail").with_context(io_err);
        let source = err.downcast_mut::<IoError>().expect("owned io source");
        *source = IoError::other("after");
        let source = err.downcast_ref::<IoError>().expect("io source");
        assert_eq!(source.to_string(), "after");
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_mut_returns_none_for_wrong_type() {
        use std::{fmt::Error as FmtError, io::Error as IoError};
        let io_err = IoError::other("test");
        let mut err = Error::new(AppErrorKind::Internal, "fail").with_context(io_err);
        assert!(err.downcast_mut::<FmtError>().is_none());
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_mut_returns_none_without_source() {
        use std::io::Error as IoError;
        let mut err = Error::new(AppErrorKind::Internal, "fail");
        assert!(err.downcast_mut::<IoError>().is_none());
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_mut_returns_none_for_shared_arc_source() {
        use std::{io::Error as IoError, sync::Arc};
        let shared = Arc::new(IoError::other("shared"));
        let source: Arc<dyn core::error::Error + Send + Sync + 'static> = shared.clone();
        let mut err = Error::new(AppErrorKind::Internal, "fail").with_source_arc(source);
        assert!(err.downcast_mut::<IoError>().is_none());
        assert_eq!(Arc::strong_count(&shared), 2);
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_mut_returns_source_for_unique_arc_source() {
        use std::{io::Error as IoError, sync::Arc};
        let shared: Arc<dyn core::error::Error + Send + Sync + 'static> =
            Arc::new(IoError::other("unique"));
        let mut err = Error::new(AppErrorKind::Internal, "fail").with_source_arc(shared);
        let source = err.downcast_mut::<IoError>().expect("unique arc source");
        assert_eq!(source.to_string(), "unique");
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_returns_boxed_source_for_owned_source() {
        use std::io::Error as IoError;
        let io_err = IoError::other("test");
        let err = Error::new(AppErrorKind::Internal, "fail").with_context(io_err);
        let source = err.downcast::<IoError>().expect("owned io source");
        assert_eq!(source.to_string(), "test");
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_returns_err_with_source_intact_for_wrong_type() {
        use std::{fmt::Error as FmtError, io::Error as IoError};
        let io_err = IoError::other("test");
        let err = Error::new(AppErrorKind::Internal, "fail").with_context(io_err);
        let err = err.downcast::<FmtError>().expect_err("wrong type");
        assert_eq!(err.kind, AppErrorKind::Internal);
        assert!(err.is::<IoError>());
        assert_eq!(
            err.downcast_ref::<IoError>()
                .expect("io source")
                .to_string(),
            "test"
        );
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_returns_err_without_source() {
        use std::io::Error as IoError;
        let err = Error::new(AppErrorKind::Internal, "fail");
        let err = err.downcast::<IoError>().expect_err("no source");
        assert_eq!(err.kind, AppErrorKind::Internal);
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_downcast_returns_err_with_source_intact_for_shared_arc() {
        use std::{io::Error as IoError, sync::Arc};
        let shared = Arc::new(IoError::other("shared"));
        let source: Arc<dyn core::error::Error + Send + Sync + 'static> = shared.clone();
        let err = Error::new(AppErrorKind::Internal, "fail").with_source_arc(source);
        let err = err.downcast::<IoError>().expect_err("shared source");
        assert!(err.is::<IoError>());
        assert_eq!(Arc::strong_count(&shared), 2);
    }

    #[test]
    fn app_result_type_alias_works() {
        let result: AppResult<u8> = Ok(42);
        assert!(result.is_ok());
        if let Ok(value) = result {
            assert_eq!(value, 42);
        }
    }

    #[test]
    fn error_chain_single_error() {
        let err = Error::new(AppErrorKind::NotFound, "not found");
        let chain: Vec<_> = err.chain().collect();
        assert_eq!(chain.len(), 1);
    }

    #[test]
    fn error_root_cause_self_when_no_source() {
        let err = Error::new(AppErrorKind::Internal, "root");
        let root = err.root_cause();
        assert!(!root.to_string().is_empty());
    }

    #[test]
    fn message_edit_policy_default_is_preserve() {
        assert_eq!(MessageEditPolicy::default(), MessageEditPolicy::Preserve);
    }

    #[cfg(feature = "serde_json")]
    #[test]
    fn error_with_details_json_attaches_details() {
        use serde_json::json;
        let err = Error::new(AppErrorKind::Validation, "invalid")
            .with_details_json(json!({"field": "email"}));
        assert!(err.details.is_some());
    }

    #[cfg(feature = "serde_json")]
    #[test]
    fn error_with_details_serializes_payload() {
        use serde::Serialize;
        #[derive(Serialize)]
        struct Extra {
            reason: &'static str
        }
        let err = Error::new(AppErrorKind::BadRequest, "invalid")
            .with_details(Extra {
                reason: "missing"
            })
            .expect("should serialize");
        assert!(err.details.is_some());
    }

    #[cfg(all(feature = "std", feature = "backtrace"))]
    #[test]
    fn error_with_backtrace_attaches_backtrace() {
        use std::backtrace::Backtrace;
        let bt = Backtrace::capture();
        let err = Error::new(AppErrorKind::Internal, "test").with_backtrace(bt);
        assert!(err.backtrace.is_some());
    }

    #[cfg(all(feature = "std", feature = "backtrace"))]
    #[test]
    fn error_with_shared_backtrace_reuses_arc() {
        use std::{backtrace::Backtrace, sync::Arc};
        let bt = Arc::new(Backtrace::capture());
        let bt_clone = Arc::clone(&bt);
        let err = Error::new(AppErrorKind::Internal, "test").with_shared_backtrace(bt);
        assert!(err.backtrace.is_some());
        assert_eq!(Arc::strong_count(&bt_clone), 2);
    }

    #[cfg(feature = "std")]
    #[test]
    fn error_with_context_shared_attachment() {
        use std::{io::Error as IoError, sync::Arc};

        use crate::app_error::core::types::ContextAttachment;
        let io_err = Arc::new(IoError::other("shared error"));
        let err = Error::new(AppErrorKind::Internal, "test")
            .with_context(ContextAttachment::Shared(io_err.clone()));
        assert!(err.source_ref().is_some());
        assert_eq!(Arc::strong_count(&io_err), 2);
    }
}