-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcustom_handler.rs
More file actions
142 lines (118 loc) · 4.13 KB
/
custom_handler.rs
File metadata and controls
142 lines (118 loc) · 4.13 KB
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
//! Custom handlers for attachments and contexts
//!
//! Handlers vs formatting hooks (see formatting_hooks.rs):
//! - Handlers (this example): Applied per-attachment/context with
//! .attach_custom() or when creating the report
//! - Formatting hooks: Registered once globally and apply to all instances of a
//! type
//!
//! Use custom handlers to control formatting for:
//! - Attachments: diagnostic data (logs, metrics, binary dumps)
//! - Contexts: structured error descriptions (validation errors, API errors)
use std::io;
use rootcause::{
handlers::{AttachmentHandler, ContextHandler},
prelude::*,
};
// Example 1: Custom attachment handler for diagnostic data
struct BinaryData(Vec<u8>);
impl core::fmt::Display for BinaryData {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{} bytes", self.0.len())
}
}
impl core::fmt::Debug for BinaryData {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "BinaryData({:?})", self.0)
}
}
// Hexdump handler for binary diagnostic data
struct Hexdump;
impl AttachmentHandler<BinaryData> for Hexdump {
fn display(data: &BinaryData, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
writeln!(f, "Hexdump ({} bytes):", data.0.len())?;
for (i, chunk) in data.0.chunks(16).enumerate() {
write!(f, "{:04x}: ", i * 16)?;
for byte in chunk {
write!(f, "{:02x} ", byte)?;
}
writeln!(f)?;
}
Ok(())
}
fn debug(data: &BinaryData, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
Self::display(data, f)
}
}
fn parse_protocol_message() -> Result<String, Report> {
let corrupt_data = BinaryData(vec![0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE]);
Err(report!(io::Error::new(
io::ErrorKind::InvalidData,
"Protocol parse error"
))
.attach("Received data:")
.attach_custom::<Hexdump, _>(corrupt_data)
.into_dynamic())
}
// Example 2: Custom context handler for structured errors
struct ValidationError {
fields: Vec<(&'static str, &'static str)>,
}
impl core::fmt::Display for ValidationError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{} validation error(s)", self.fields.len())
}
}
impl core::fmt::Debug for ValidationError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ValidationError")
.field("fields", &self.fields)
.finish()
}
}
impl std::error::Error for ValidationError {}
// Pretty list handler for validation errors
struct ValidationList;
impl ContextHandler<ValidationError> for ValidationList {
fn display(error: &ValidationError, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
writeln!(f, "Validation failed:")?;
for (field, reason) in &error.fields {
writeln!(f, " • {}: {}", field, reason)?;
}
Ok(())
}
fn debug(error: &ValidationError, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
Self::display(error, f)
}
fn source(error: &ValidationError) -> Option<&(dyn std::error::Error + 'static)> {
let _ = error;
None
}
}
fn validate_user_input() -> Result<(), Report> {
let validation_error = ValidationError {
fields: vec![
("email", "invalid format"),
("age", "must be positive"),
("username", "too short (min 3 chars)"),
],
};
// context_custom uses the custom handler for the error description
Err(
report!(io::Error::new(io::ErrorKind::InvalidInput, "Bad request"))
.context_custom::<ValidationList, _>(validation_error)
.into_dynamic(),
)
}
fn main() {
println!("Example 1: Custom attachment handler\n");
match parse_protocol_message() {
Ok(_) => println!("Success"),
Err(error) => eprintln!("{error}\n"),
}
println!("Example 2: Custom context handler\n");
match validate_user_input() {
Ok(()) => println!("Success"),
Err(error) => eprintln!("{error}"),
}
}