masterror 0.31.1

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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
// SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
//
// SPDX-License-Identifier: MIT

use alloc::string::{String, ToString};
use core::{
    error::Error as CoreError,
    fmt::{Formatter, Result as FmtResult}
};

#[cfg(test)]
use super::display_mode::DisplayMode;
#[cfg(test)]
use super::display_mode::force_display_mode;
use super::{error::Error, types::MessageEditPolicy};
use crate::app_error::{
    metadata::{FieldRedaction, FieldValue, Metadata},
    redaction::{hash_field_value, mask_last4_field_value}
};

impl Error {
    ///
    /// Selected by the `Display` implementation when [`DisplayMode::current`]
    /// returns [`DisplayMode::Prod`]. The output never contains ANSI escape
    /// sequences.
    ///
    /// # Arguments
    ///
    /// * `f` - Formatter to write output to
    pub(crate) fn fmt_prod(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, r#"{{"kind":"{:?}","code":"{}""#, self.kind, self.code)?;
        if !matches!(self.edit_policy, MessageEditPolicy::Redact)
            && let Some(msg) = &self.message
        {
            write!(f, ",\"message\":\"")?;
            write_json_escaped(f, msg.as_ref())?;
            write!(f, "\"")?;
        }
        write_json_metadata_section(f, &self.metadata)?;
        write!(f, "}}")
    }

    /// Formats the error as a multi-line human-readable report (kind, code,
    /// message, source chain, redaction-aware metadata).
    ///
    /// Selected by the `Display` implementation when [`DisplayMode::current`]
    /// returns [`DisplayMode::Local`]. The `colored` feature applies ANSI
    /// styling to this layout when the terminal supports it.
    ///
    /// # Arguments
    ///
    /// * `f` - Formatter to write output to
    pub(crate) fn fmt_local(&self, f: &mut Formatter<'_>) -> FmtResult {
        #[cfg(feature = "colored")]
        use crate::colored::style;

        writeln!(f, "Error: {}", self.kind)?;
        #[cfg(feature = "colored")]
        writeln!(f, "Code: {}", style::error_code(self.code.to_string()))?;
        #[cfg(not(feature = "colored"))]
        writeln!(f, "Code: {}", self.code)?;
        if !matches!(self.edit_policy, MessageEditPolicy::Redact)
            && let Some(msg) = &self.message
        {
            #[cfg(feature = "colored")]
            writeln!(f, "Message: {}", style::error_message(msg))?;
            #[cfg(not(feature = "colored"))]
            writeln!(f, "Message: {msg}")?;
        }
        if let Some(source) = &self.source {
            writeln!(f)?;
            let mut current: &dyn CoreError = source.as_dyn();
            let mut depth = 0;
            while depth < 10 {
                #[cfg(feature = "colored")]
                writeln!(
                    f,
                    "  {}: {}",
                    style::source_context("Caused by"),
                    style::source_context(current.to_string())
                )?;
                #[cfg(not(feature = "colored"))]
                writeln!(f, "  Caused by: {current}")?;
                if let Some(next) = current.source() {
                    current = next;
                    depth += 1;
                } else {
                    break;
                }
            }
        }
        write_local_metadata_section(f, &self.metadata)
    }

    /// Formats the error as JSON with additional context (`source_chain` and
    /// redaction-aware metadata).
    ///
    /// Selected by the `Display` implementation when [`DisplayMode::current`]
    /// returns [`DisplayMode::Staging`]. The output never contains ANSI
    /// escape sequences.
    ///
    /// # Arguments
    ///
    /// * `f` - Formatter to write output to
    pub(crate) fn fmt_staging(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, r#"{{"kind":"{:?}","code":"{}""#, self.kind, self.code)?;
        if !matches!(self.edit_policy, MessageEditPolicy::Redact)
            && let Some(msg) = &self.message
        {
            write!(f, ",\"message\":\"")?;
            write_json_escaped(f, msg.as_ref())?;
            write!(f, "\"")?;
        }
        if let Some(source) = &self.source {
            write!(f, r#","source_chain":["#)?;
            let mut current: &dyn CoreError = source.as_dyn();
            let mut depth = 0;
            let mut first = true;
            while depth < 5 {
                if !first {
                    write!(f, ",")?;
                }
                first = false;
                write!(f, "\"")?;
                write_json_escaped(f, &current.to_string())?;
                write!(f, "\"")?;
                if let Some(next) = current.source() {
                    current = next;
                    depth += 1;
                } else {
                    break;
                }
            }
            write!(f, "]")?;
        }
        write_json_metadata_section(f, &self.metadata)?;
        write!(f, "}}")
    }
}

/// Metadata value prepared for the local layout after applying redaction.
enum LocalFieldValue<'a> {
    /// Public value rendered as-is.
    Raw(&'a FieldValue),
    /// Value replaced by the redaction placeholder.
    Placeholder,
    /// Hashed or masked textual representation.
    Owned(String)
}

/// Writes the `,"metadata":{...}` JSON section applying field redaction.
///
/// Fields marked [`FieldRedaction::Redact`] render as the placeholder,
/// [`FieldRedaction::Hash`] as a SHA-256 hex digest and
/// [`FieldRedaction::Last4`] as a masked value. Fields whose masking yields
/// no value are omitted; if nothing remains, the section is skipped
/// entirely.
fn write_json_metadata_section(f: &mut Formatter<'_>, metadata: &Metadata) -> FmtResult {
    let mut wrote_any = false;
    for (name, value, redaction) in metadata.iter_with_redaction() {
        let masked = match redaction {
            FieldRedaction::Last4 => match mask_last4_field_value(value) {
                Some(masked) => Some(masked),
                None => continue
            },
            _ => None
        };
        if wrote_any {
            write!(f, ",")?;
        } else {
            write!(f, r#","metadata":{{"#)?;
            wrote_any = true;
        }
        write!(f, r#""{name}":"#)?;
        match redaction {
            FieldRedaction::None => write_metadata_value(f, value)?,
            FieldRedaction::Redact => write!(f, "\"{}\"", FieldRedaction::REDACTED_PLACEHOLDER)?,
            FieldRedaction::Hash => write!(f, "\"{}\"", hash_field_value(value))?,
            FieldRedaction::Last4 => {
                write!(f, "\"")?;
                write_json_escaped(f, masked.as_deref().unwrap_or_default())?;
                write!(f, "\"")?;
            }
        }
    }
    if wrote_any {
        write!(f, "}}")?;
    }
    Ok(())
}

/// Writes the `Context:` block of the local layout applying field redaction.
///
/// Applies the same policies as [`write_json_metadata_section`]; the header
/// is skipped when every field is omitted.
fn write_local_metadata_section(f: &mut Formatter<'_>, metadata: &Metadata) -> FmtResult {
    let mut wrote_header = false;
    for (name, value, redaction) in metadata.iter_with_redaction() {
        let rendered = match redaction {
            FieldRedaction::None => LocalFieldValue::Raw(value),
            FieldRedaction::Redact => LocalFieldValue::Placeholder,
            FieldRedaction::Hash => LocalFieldValue::Owned(hash_field_value(value)),
            FieldRedaction::Last4 => match mask_last4_field_value(value) {
                Some(masked) => LocalFieldValue::Owned(masked),
                None => continue
            }
        };
        if !wrote_header {
            writeln!(f)?;
            writeln!(f, "Context:")?;
            wrote_header = true;
        }
        #[cfg(feature = "colored")]
        write!(f, "  {}: ", crate::colored::style::metadata_key(name))?;
        #[cfg(not(feature = "colored"))]
        write!(f, "  {name}: ")?;
        match rendered {
            LocalFieldValue::Raw(value) => writeln!(f, "{value}")?,
            LocalFieldValue::Placeholder => {
                writeln!(f, "{}", FieldRedaction::REDACTED_PLACEHOLDER)?;
            }
            LocalFieldValue::Owned(text) => writeln!(f, "{text}")?
        }
    }
    Ok(())
}

/// Writes a string with JSON escaping.
fn write_json_escaped(f: &mut Formatter<'_>, s: &str) -> FmtResult {
    for ch in s.chars() {
        match ch {
            '"' => write!(f, "\\\"")?,
            '\\' => write!(f, "\\\\")?,
            '\n' => write!(f, "\\n")?,
            '\r' => write!(f, "\\r")?,
            '\t' => write!(f, "\\t")?,
            ch if ch.is_control() => write!(f, "\\u{:04x}", ch as u32)?,
            ch => write!(f, "{ch}")?
        }
    }
    Ok(())
}

/// Writes a metadata field value in JSON format.
fn write_metadata_value(f: &mut Formatter<'_>, value: &FieldValue) -> FmtResult {
    use crate::app_error::metadata::FieldValue;
    match value {
        FieldValue::Str(s) => {
            write!(f, "\"")?;
            write_json_escaped(f, s.as_ref())?;
            write!(f, "\"")
        }
        FieldValue::I64(v) => write!(f, "{v}"),
        FieldValue::U64(v) => write!(f, "{v}"),
        FieldValue::F64(v) => {
            if v.is_finite() {
                write!(f, "{v}")
            } else {
                write!(f, "null")
            }
        }
        FieldValue::Bool(v) => write!(f, "{v}"),
        FieldValue::Uuid(v) => write!(f, "\"{v}\""),
        FieldValue::Duration(v) => {
            write!(
                f,
                r#"{{"secs":{},"nanos":{}}}"#,
                v.as_secs(),
                v.subsec_nanos()
            )
        }
        FieldValue::Ip(v) => write!(f, "\"{v}\""),
        #[cfg(feature = "serde_json")]
        FieldValue::Json(v) => write!(f, "{v}")
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Write as _;

    use sha2::{Digest, Sha256};

    use super::*;
    use crate::{AppError, field};

    fn sha256_hex(input: &[u8]) -> String {
        let mut hasher = Sha256::new();
        hasher.update(input);
        hasher
            .finalize()
            .iter()
            .fold(String::with_capacity(64), |mut acc, byte| {
                let _ = write!(&mut acc, "{byte:02x}");
                acc
            })
    }

    #[test]
    fn display_mode_override_takes_priority() {
        let _guard = force_display_mode(DisplayMode::Staging);
        assert_eq!(DisplayMode::current(), DisplayMode::Staging);
    }

    #[test]
    fn display_dispatches_prod_layout() {
        let _guard = force_display_mode(DisplayMode::Prod);
        let error = AppError::not_found("missing user");
        let output = format!("{error}");
        assert!(output.starts_with(r#"{"kind":"NotFound""#), "{output}");
        assert!(output.contains(r#""code":"NOT_FOUND""#));
        assert!(output.contains(r#""message":"missing user""#));
        assert!(!output.contains('\u{1b}'));
    }

    #[cfg(feature = "std")]
    #[test]
    fn display_dispatches_staging_layout() {
        use std::io::Error as IoError;
        let _guard = force_display_mode(DisplayMode::Staging);
        let error = AppError::network("upstream down").with_source(IoError::other("timeout"));
        let output = format!("{error}");
        assert!(output.starts_with(r#"{"kind":"Network""#), "{output}");
        assert!(output.contains(r#""source_chain":["timeout"]"#));
        assert!(!output.contains('\u{1b}'));
    }

    #[test]
    fn display_dispatches_local_layout() {
        let _guard = force_display_mode(DisplayMode::Local);
        let error = AppError::not_found("missing user");
        let output = format!("{error}");
        assert!(output.contains("Error:"));
        assert!(output.contains("Code: NOT_FOUND"));
        assert!(output.contains("missing user"));
    }

    #[test]
    fn fmt_prod_outputs_json() {
        let error = AppError::not_found("User not found");
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""kind":"NotFound""#));
        assert!(output.contains(r#""code":"NOT_FOUND""#));
        assert!(output.contains(r#""message":"User not found""#));
    }

    #[test]
    fn fmt_prod_excludes_redacted_message() {
        let error = AppError::internal("secret").redactable();
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(!output.contains("secret"));
    }

    #[test]
    fn fmt_prod_includes_metadata() {
        let error = AppError::not_found("User not found").with_field(field::u64("user_id", 12345));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""metadata""#));
        assert!(output.contains(r#""user_id":12345"#));
    }

    #[test]
    fn fmt_prod_excludes_sensitive_metadata() {
        let error = AppError::internal("Error").with_field(field::str("password", "secret"));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(!output.contains("secret"));
        assert!(output.contains(r#""password":"[REDACTED]""#));
    }

    #[test]
    fn hash_redaction_renders_hex_digest_in_all_modes() {
        let expected = sha256_hex(b"super-secret");
        let error = AppError::internal("Error").with_field(
            field::str("fingerprint", "super-secret").with_redaction(FieldRedaction::Hash)
        );
        let prod = format!("{}", error.fmt_prod_wrapper());
        let staging = format!("{}", error.fmt_staging_wrapper());
        let local = format!("{}", error.fmt_local_wrapper());
        for output in [&prod, &staging, &local] {
            assert!(output.contains(&expected), "{output}");
            assert!(!output.contains("super-secret"), "{output}");
        }
        assert!(prod.contains(&format!(r#""fingerprint":"{expected}""#)));
        assert!(staging.contains(&format!(r#""fingerprint":"{expected}""#)));
        assert!(local.contains(&format!("fingerprint: {expected}")));
    }

    #[test]
    fn last4_redaction_masks_value_in_all_modes() {
        let error = AppError::internal("Error").with_field(
            field::str("card_number", "4111111111111111").with_redaction(FieldRedaction::Last4)
        );
        let prod = format!("{}", error.fmt_prod_wrapper());
        let staging = format!("{}", error.fmt_staging_wrapper());
        let local = format!("{}", error.fmt_local_wrapper());
        for output in [&prod, &staging, &local] {
            assert!(output.contains("************1111"), "{output}");
            assert!(!output.contains("4111111111111111"), "{output}");
        }
    }

    #[test]
    fn last4_redaction_omits_unmaskable_field() {
        let error = AppError::internal("Error")
            .with_field(field::bool("consent", true).with_redaction(FieldRedaction::Last4));
        let prod = format!("{}", error.fmt_prod_wrapper());
        let staging = format!("{}", error.fmt_staging_wrapper());
        let local = format!("{}", error.fmt_local_wrapper());
        assert!(!prod.contains("metadata"), "{prod}");
        assert!(!staging.contains("metadata"), "{staging}");
        assert!(!local.contains("Context:"), "{local}");
        for output in [&prod, &staging, &local] {
            assert!(!output.contains("consent"), "{output}");
        }
    }

    #[test]
    fn redact_policy_uses_placeholder_in_local_layout() {
        let error = AppError::internal("Error").with_field(field::str("password", "hunter2"));
        let output = format!("{}", error.fmt_local_wrapper());
        assert!(output.contains("password: [REDACTED]"), "{output}");
        assert!(!output.contains("hunter2"));
    }

    #[test]
    fn fmt_local_hides_redacted_message() {
        let error = AppError::internal("sensitive data").redactable();
        let output = format!("{}", error.fmt_local_wrapper());
        assert!(!output.contains("sensitive data"));
        assert!(!output.contains("Message:"));
    }

    #[test]
    fn fmt_local_outputs_human_readable() {
        let error = AppError::not_found("User not found");
        let output = format!("{}", error.fmt_local_wrapper());
        assert!(output.contains("Error:"));
        assert!(output.contains("Code: NOT_FOUND"));
        assert!(output.contains("Message: User not found"));
    }

    #[cfg(feature = "std")]
    #[test]
    fn fmt_local_includes_source_chain() {
        use std::io::Error as IoError;
        let io_err = IoError::other("connection failed");
        let error = AppError::internal("Database error").with_source(io_err);
        let output = format!("{}", error.fmt_local_wrapper());
        assert!(output.contains("Caused by"));
        assert!(output.contains("connection failed"));
    }

    #[test]
    fn fmt_staging_outputs_json_with_context() {
        let error = AppError::service("Service unavailable");
        let output = format!("{}", error.fmt_staging_wrapper());
        assert!(output.contains(r#""kind":"Service""#));
        assert!(output.contains(r#""code":"SERVICE""#));
    }

    #[cfg(feature = "std")]
    #[test]
    fn fmt_staging_includes_source_chain() {
        use std::io::Error as IoError;
        let io_err = IoError::other("timeout");
        let error = AppError::network("Network error").with_source(io_err);
        let output = format!("{}", error.fmt_staging_wrapper());
        assert!(output.contains(r#""source_chain""#));
        assert!(output.contains("timeout"));
    }

    #[test]
    fn fmt_prod_escapes_special_chars() {
        let error = AppError::internal("Line\nwith\"quotes\"");
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r"\n"));
        assert!(output.contains(r#"\""#));
    }

    #[test]
    fn fmt_prod_handles_infinity_in_metadata() {
        let error = AppError::internal("Error").with_field(field::f64("ratio", f64::INFINITY));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains("null"));
    }

    #[test]
    fn fmt_prod_formats_duration_metadata() {
        use core::time::Duration;
        let error = AppError::internal("Error")
            .with_field(field::duration("elapsed", Duration::from_millis(1500)));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""secs":1"#));
        assert!(output.contains(r#""nanos":500000000"#));
    }

    #[test]
    fn fmt_prod_formats_bool_metadata() {
        let error = AppError::internal("Error").with_field(field::bool("active", true));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""active":true"#));
    }

    #[cfg(feature = "std")]
    #[test]
    fn fmt_prod_formats_ip_metadata() {
        use std::net::IpAddr;
        let ip: IpAddr = "192.168.1.1".parse().unwrap();
        let error = AppError::internal("Error").with_field(field::ip("client_ip", ip));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""client_ip":"192.168.1.1""#));
    }

    #[test]
    fn fmt_prod_formats_uuid_metadata() {
        use uuid::Uuid;
        let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
        let error = AppError::internal("Error").with_field(field::uuid("request_id", uuid));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""request_id":"550e8400-e29b-41d4-a716-446655440000""#));
    }

    #[cfg(feature = "serde_json")]
    #[test]
    fn fmt_prod_formats_json_metadata() {
        let json = serde_json::json!({"nested": "value"});
        let error = AppError::internal("Error").with_field(field::json("data", json));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""data":"#));
    }

    #[test]
    fn fmt_prod_without_message() {
        let error = AppError::bare(crate::kind::AppErrorKind::Internal);
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""kind":"Internal""#));
        assert!(!output.contains(r#""message""#));
    }

    #[test]
    fn fmt_local_without_message() {
        let error = AppError::bare(crate::kind::AppErrorKind::BadRequest);
        let output = format!("{}", error.fmt_local_wrapper());
        assert!(output.contains("Error:"));
        assert!(!output.contains("Message:"));
    }

    #[test]
    fn fmt_local_with_metadata() {
        let error = AppError::internal("Error")
            .with_field(field::str("region", "value"))
            .with_field(field::i64("count", -42));
        let output = format!("{}", error.fmt_local_wrapper());
        assert!(output.contains("Context:"));
        assert!(output.contains("region: value"));
        assert!(output.contains("count: -42"));
    }

    #[test]
    fn fmt_staging_without_message() {
        let error = AppError::bare(crate::kind::AppErrorKind::Timeout);
        let output = format!("{}", error.fmt_staging_wrapper());
        assert!(output.contains(r#""kind":"Timeout""#));
        assert!(!output.contains(r#""message""#));
    }

    #[test]
    fn fmt_staging_with_metadata() {
        let error = AppError::service("Service error").with_field(field::u64("retry_count", 3));
        let output = format!("{}", error.fmt_staging_wrapper());
        assert!(output.contains(r#""metadata""#));
        assert!(output.contains(r#""retry_count":3"#));
    }

    #[test]
    fn fmt_staging_with_redacted_message() {
        let error = AppError::internal("sensitive data").redactable();
        let output = format!("{}", error.fmt_staging_wrapper());
        assert!(!output.contains("sensitive data"));
    }

    #[test]
    fn fmt_prod_escapes_control_chars() {
        let error = AppError::internal("test\x00\x1F");
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r"\u0000"));
        assert!(output.contains(r"\u001f"));
    }

    #[test]
    fn fmt_prod_escapes_tab_and_carriage_return() {
        let error = AppError::internal("line\ttab\rreturn");
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r"\t"));
        assert!(output.contains(r"\r"));
    }

    #[test]
    fn fmt_prod_with_multiple_metadata_fields() {
        let error = AppError::not_found("test")
            .with_field(field::str("first", "value1"))
            .with_field(field::u64("second", 42))
            .with_field(field::bool("third", true));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""first":"value1""#));
        assert!(output.contains(r#""second":42"#));
        assert!(output.contains(r#""third":true"#));
    }

    #[test]
    fn fmt_prod_escapes_backslash() {
        let error = AppError::internal("path\\to\\file");
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r"path\\to\\file"));
    }

    #[test]
    fn fmt_prod_with_i64_metadata() {
        let error = AppError::internal("test").with_field(field::i64("count", -100));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""count":-100"#));
    }

    #[test]
    fn fmt_prod_with_string_metadata() {
        let error = AppError::internal("test").with_field(field::str("name", "value"));
        let output = format!("{}", error.fmt_prod_wrapper());
        assert!(output.contains(r#""name":"value""#));
    }

    #[cfg(feature = "std")]
    #[test]
    fn fmt_local_with_deep_source_chain() {
        use std::io::{Error as IoError, ErrorKind};
        let io1 = IoError::new(ErrorKind::NotFound, "level 1");
        let io2 = IoError::other(io1);
        let error = AppError::internal("top").with_source(io2);
        let output = format!("{}", error.fmt_local_wrapper());
        assert!(output.contains("Caused by"));
        assert!(output.contains("level 1"));
    }

    #[test]
    fn fmt_staging_with_multiple_metadata_fields() {
        let error = AppError::service("error")
            .with_field(field::str("key1", "value1"))
            .with_field(field::u64("key2", 123))
            .with_field(field::bool("key3", false));
        let output = format!("{}", error.fmt_staging_wrapper());
        assert!(output.contains(r#""key1":"value1""#));
        assert!(output.contains(r#""key2":123"#));
        assert!(output.contains(r#""key3":false"#));
    }

    #[test]
    fn fmt_staging_with_deep_source_chain() {
        use std::io::{Error as IoError, ErrorKind};
        let io1 = IoError::new(ErrorKind::NotFound, "inner error");
        let io2 = IoError::other(io1);
        let error = AppError::service("outer").with_source(io2);
        let output = format!("{}", error.fmt_staging_wrapper());
        assert!(output.contains(r#""source_chain""#));
        assert!(output.contains("inner error"));
    }

    #[test]
    fn fmt_staging_with_redacted_and_public_metadata() {
        let error = AppError::internal("test")
            .with_field(field::str("public", "visible"))
            .with_field(field::str("password", "secret"));
        let output = format!("{}", error.fmt_staging_wrapper());
        assert!(output.contains(r#""public":"visible""#));
        assert!(output.contains(r#""password":"[REDACTED]""#));
        assert!(!output.contains("secret"));
    }

    impl Error {
        fn fmt_prod_wrapper(&self) -> FormatterWrapper<'_> {
            FormatterWrapper {
                error: self,
                mode:  FormatterMode::Prod
            }
        }

        fn fmt_local_wrapper(&self) -> FormatterWrapper<'_> {
            FormatterWrapper {
                error: self,
                mode:  FormatterMode::Local
            }
        }

        fn fmt_staging_wrapper(&self) -> FormatterWrapper<'_> {
            FormatterWrapper {
                error: self,
                mode:  FormatterMode::Staging
            }
        }
    }

    enum FormatterMode {
        Prod,
        Local,
        Staging
    }

    struct FormatterWrapper<'a> {
        error: &'a Error,
        mode:  FormatterMode
    }

    impl core::fmt::Display for FormatterWrapper<'_> {
        fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
            match self.mode {
                FormatterMode::Prod => self.error.fmt_prod(f),
                FormatterMode::Local => self.error.fmt_local(f),
                FormatterMode::Staging => self.error.fmt_staging(f)
            }
        }
    }
}