pub struct Code { /* private fields */ }Expand description
Waddling diagnostic code: SEVERITY.COMPONENT.PRIMARY.SEQUENCE
A lightweight, type-safe diagnostic code for the Waddling ecosystem. Supports all severity levels (errors, warnings, success, info, traces).
§Format
SEVERITY.COMPONENT.PRIMARY.SEQUENCE → E.CRYPTO.SALT.001
Where SEVERITY is:
E= Error (operation failed)W= Warning (potential issue)C= Critical (severe issue)B= Blocked (execution blocked)S= Success (operation succeeded)K= Completed (task finished)I= Info (informational events)T= Trace (execution traces, probes)
§Examples
use waddling_errors::{Code, Severity};
// Using constructor methods (recommended)
const ERR_SALT: Code = Code::error("CRYPTO", "SALT", 1);
const WARN_DEPR: Code = Code::warning("API", "DEPR", 1);
const SUCCESS: Code = Code::success("BUILD", "DONE", 999);
assert_eq!(ERR_SALT.code(), "E.CRYPTO.SALT.001");
assert_eq!(WARN_DEPR.code(), "W.API.DEPR.001");
assert_eq!(SUCCESS.code(), "S.BUILD.DONE.999");§Using the prelude for ergonomic imports
use waddling_errors::prelude::*;
const ERR_PARSE: Code = error("parser", "DOM", 1);
const WARN_API: Code = warning("api", "DEPR", 10);Implementations§
Source§impl Code
impl Code
Sourcepub const fn new(
severity: Severity,
component: &'static str,
primary: &'static str,
sequence: u16,
) -> Self
pub const fn new( severity: Severity, component: &'static str, primary: &'static str, sequence: u16, ) -> Self
Create a new code with explicit severity
§Panics
Panics if:
- sequence > 999
- component length < 2 or > 12
- primary length < 2 or > 12
Examples found in repository?
More examples
14const ERR_INVALID_SALT: ErrorCode = ErrorCode::new(Severity::Error, "CRYPTO", "SALT", 1);
15const ERR_PARSE_FAILED: ErrorCode = ErrorCode::new(Severity::Error, "PARSER", "SYNTAX", 2);
16const ERR_AUTH_FAILED: ErrorCode = ErrorCode::new(Severity::Error, "AUTH", "CRED", 3);
17
18// WARNING (W): Potential issue
19const WARN_DEPRECATED: ErrorCode = ErrorCode::new(Severity::Warning, "API", "DEPR", 1);
20const WARN_PERF_HIT: ErrorCode = ErrorCode::new(Severity::Warning, "PERF", "SLOW", 2);
21const WARN_EDGE_CASE: ErrorCode = ErrorCode::new(Severity::Warning, "VALID", "EDGE", 3);
22
23// CRITICAL (C): Severe issue
24const CRIT_DATA_CORRUPT: ErrorCode = ErrorCode::new(Severity::Critical, "DATA", "CORRUPT", 1);
25const CRIT_SEC_BREACH: ErrorCode = ErrorCode::new(Severity::Critical, "SEC", "BREACH", 2);
26const CRIT_MEM_LEAK: ErrorCode = ErrorCode::new(Severity::Critical, "MEM", "LEAK", 3);
27
28// BLOCKED (B): Execution blocked/waiting
29const BLOCK_DEADLOCK: ErrorCode = ErrorCode::new(Severity::Blocked, "THREAD", "DEADLOCK", 1);
30const BLOCK_IO_WAIT: ErrorCode = ErrorCode::new(Severity::Blocked, "IO", "WAIT", 2);
31const BLOCK_NET_DOWN: ErrorCode = ErrorCode::new(Severity::Blocked, "NET", "DOWN", 3);
32
33// SUCCESS (S): Operation succeeded
34const SUCCESS_BUILD: ErrorCode = ErrorCode::new(Severity::Success, "BUILD", "DONE", 1);
35const SUCCESS_TEST: ErrorCode = ErrorCode::new(Severity::Success, "TEST", "PASS", 2);
36
37// COMPLETED (K): Task/phase completed
38const COMPLETE_PARSE: ErrorCode = ErrorCode::new(Severity::Completed, "PARSE", "DONE", 1);
39const COMPLETE_TYPECHECK: ErrorCode = ErrorCode::new(Severity::Completed, "TYPE", "CHECK", 2);
40
41// INFO (I): Informational events
42const INFO_SERVER_START: ErrorCode = ErrorCode::new(Severity::Info, "SERVER", "START", 1);
43const INFO_CONFIG_LOAD: ErrorCode = ErrorCode::new(Severity::Info, "CONFIG", "LOAD", 2);
44
45// TRACE (T): Execution traces, probes
46const TRACE_THREAD_SPAWN: ErrorCode = ErrorCode::new(Severity::Trace, "PROBE", "THREAD", 1);
47const TRACE_LOCK_ACQUIRE: ErrorCode = ErrorCode::new(Severity::Trace, "PROBE", "LOCK", 2);Sourcepub const fn error(
component: &'static str,
primary: &'static str,
sequence: u16,
) -> Self
pub const fn error( component: &'static str, primary: &'static str, sequence: u16, ) -> Self
Create an error code (E)
§Examples
use waddling_errors::Code;
const ERR: Code = Code::error("CRYPTO", "SALT", 1);
assert_eq!(ERR.code(), "E.CRYPTO.SALT.001");Sourcepub const fn warning(
component: &'static str,
primary: &'static str,
sequence: u16,
) -> Self
pub const fn warning( component: &'static str, primary: &'static str, sequence: u16, ) -> Self
Create a warning code (W)
Sourcepub const fn critical(
component: &'static str,
primary: &'static str,
sequence: u16,
) -> Self
pub const fn critical( component: &'static str, primary: &'static str, sequence: u16, ) -> Self
Create a critical code (C)
Sourcepub const fn blocked(
component: &'static str,
primary: &'static str,
sequence: u16,
) -> Self
pub const fn blocked( component: &'static str, primary: &'static str, sequence: u16, ) -> Self
Create a blocked code (B)
Sourcepub const fn success(
component: &'static str,
primary: &'static str,
sequence: u16,
) -> Self
pub const fn success( component: &'static str, primary: &'static str, sequence: u16, ) -> Self
Create a success code (S)
Sourcepub const fn completed(
component: &'static str,
primary: &'static str,
sequence: u16,
) -> Self
pub const fn completed( component: &'static str, primary: &'static str, sequence: u16, ) -> Self
Create a completed code (K)
Sourcepub const fn info(
component: &'static str,
primary: &'static str,
sequence: u16,
) -> Self
pub const fn info( component: &'static str, primary: &'static str, sequence: u16, ) -> Self
Create an info code (I)
Sourcepub const fn trace(
component: &'static str,
primary: &'static str,
sequence: u16,
) -> Self
pub const fn trace( component: &'static str, primary: &'static str, sequence: u16, ) -> Self
Create a trace code (T)
Sourcepub fn code(&self) -> String
pub fn code(&self) -> String
Get the full error code (e.g., “E.CRYPTO.SALT.001”)
Examples found in repository?
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 write!(f, "[MYAPP.{}] {}", self.code.code(), self.message)
50 }
51}
52
53impl std::error::Error for AppError {}
54
55// ============================================================================
56// Usage Examples
57// ============================================================================
58
59fn validate_age(age: i32) -> Result<(), AppError> {
60 if !(0..=150).contains(&age) {
61 return Err(AppError::new(
62 ERR_INVALID_INPUT,
63 format!("Age {} is out of valid range (0-150)", age),
64 ));
65 }
66 Ok(())
67}
68
69fn find_user(id: u32) -> Result<String, AppError> {
70 // Simulate database lookup
71 if id == 0 {
72 return Err(AppError::new(ERR_NOT_FOUND, "User not found"));
73 }
74 Ok(format!("User #{}", id))
75}
76
77fn process_with_warnings(data: &str) -> Result<String, AppError> {
78 if data.contains("old_api") {
79 // Even with warnings, we can continue - but report it
80 eprintln!("[WARN.{}] Using deprecated API", WARN_DEPRECATED.code());
81 }
82 Ok(data.to_uppercase())
83}
84
85// ============================================================================
86// Alternative: Direct Code Returns (Ultra Minimal)
87// ============================================================================
88
89fn quick_validate(value: i32) -> Result<i32, Code> {
90 if value < 0 {
91 return Err(ERR_INVALID_INPUT);
92 }
93 Ok(value * 2)
94}
95
96// ============================================================================
97// Main Demo
98// ============================================================================
99
100fn main() {
101 println!("🦆 Waddling-Errors Standalone Demo 🦆\n");
102 println!("Zero external dependencies - just pure error codes!\n");
103
104 // Example 1: Custom error type
105 println!("═══════════════════════════════════════════════════");
106 println!("Example 1: Custom Error Type with ErrorCode");
107 println!("═══════════════════════════════════════════════════");
108
109 match validate_age(-5) {
110 Ok(_) => println!("✓ Age valid"),
111 Err(e) => {
112 println!("✗ Error: {}", e);
113 println!(" Code: {}", e.code().code());
114 println!(" Severity: {:?}", e.code().severity());
115 }
116 }
117 println!();
118
119 // Example 2: Not found error
120 println!("═══════════════════════════════════════════════════");
121 println!("Example 2: Data Not Found");
122 println!("═══════════════════════════════════════════════════");
123
124 match find_user(0) {
125 Ok(user) => println!("✓ Found: {}", user),
126 Err(e) => {
127 println!("✗ Error: {}", e);
128 println!(" Code: {}", e.code().code());
129 }
130 }
131 println!();
132
133 // Example 3: Warnings
134 println!("═══════════════════════════════════════════════════");
135 println!("Example 3: Warnings");
136 println!("═══════════════════════════════════════════════════");
137
138 match process_with_warnings("old_api_call()") {
139 Ok(result) => println!("✓ Processed (with warnings): {}", result),
140 Err(e) => println!("✗ Failed: {}", e),
141 }
142 println!();
143
144 // Example 4: Direct ErrorCode returns (ultra minimal)
145 println!("═══════════════════════════════════════════════════");
146 println!("Example 4: Direct ErrorCode Returns (Ultra Minimal)");
147 println!("═══════════════════════════════════════════════════");
148
149 match quick_validate(-10) {
150 Ok(val) => println!("✓ Result: {}", val),
151 Err(code) => {
152 println!("✗ Failed with code: {}", code.code());
153 println!(" Just the error code - no wrapper type needed!");
154 }
155 }
156 println!();
157
158 // Example 5: Success codes
159 println!("═══════════════════════════════════════════════════");
160 println!("Example 5: Success Codes (Active Diagnostic Systems)");
161 println!("═══════════════════════════════════════════════════");
162
163 println!("Task completed!");
164 println!(" Code: {}", SUCCESS_COMPLETE.code());
165 println!(" Positive: {}", SUCCESS_COMPLETE.severity().is_positive());
166 println!(" Active systems can celebrate success! 🎉");
167 println!();
168
169 // Summary
170 println!("═══════════════════════════════════════════════════");
171 println!("Key Takeaways");
172 println!("═══════════════════════════════════════════════════");
173 println!("✓ No external dependencies (thiserror/anyhow optional)");
174 println!("✓ Error codes are const fn (zero runtime cost)");
175 println!("✓ Works in no_std environments");
176 println!("✓ ~500 bytes binary size overhead");
177 println!("✓ DIY error types or direct ErrorCode returns");
178 println!("✓ Full control over error handling");
179 println!("\n🦆 Pure, lightweight, flexible! 🦆\n");
180}More examples
9fn main() {
10 // Force the compiler to include the codes and hashing
11 println!("{}", ERR1.code());
12 println!("{}", ERR2.code());
13 println!("{}", ERR3.code());
14
15 #[cfg(feature = "hash")]
16 {
17 println!("Hash1: {}", ERR1.hash());
18 println!("Hash2: {}", ERR2.hash());
19 println!("Hash3: {}", ERR3.hash());
20 }
21}82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 match self {
84 CryptoError::InvalidSaltLength(code, expected, got) => {
85 write!(
86 f,
87 "[MYLIB.{}] Invalid salt length: expected {} bytes, got {} bytes",
88 code.code(),
89 expected,
90 got
91 )
92 }
93 CryptoError::InvalidKeyLength(code, expected, got) => {
94 write!(
95 f,
96 "[MYLIB.{}] Invalid key length: expected {} bytes, got {} bytes",
97 code.code(),
98 expected,
99 got
100 )
101 }
102 CryptoError::MacVerificationFailed(code) => {
103 write!(f, "[MYLIB.{}] MAC verification failed", code.code())
104 }
105 }
106 }
107}
108
109impl std::error::Error for CryptoError {}
110
111// ============================================================================
112// Usage Examples
113// ============================================================================
114
115fn validate_salt(salt: &[u8]) -> Result<(), CryptoError> {
116 const EXPECTED_LEN: usize = 32;
117 if salt.len() != EXPECTED_LEN {
118 return Err(CryptoError::InvalidSaltLength(
119 ERR_INVALID_SALT,
120 EXPECTED_LEN,
121 salt.len(),
122 ));
123 }
124 Ok(())
125}
126
127fn validate_key(key: &[u8]) -> Result<(), CryptoError> {
128 const EXPECTED_LEN: usize = 32;
129 if key.len() != EXPECTED_LEN {
130 return Err(CryptoError::InvalidKeyLength(
131 ERR_INVALID_KEY,
132 EXPECTED_LEN,
133 key.len(),
134 ));
135 }
136 Ok(())
137}
138
139fn verify_mac(data: &[u8], mac: &[u8]) -> Result<(), CryptoError> {
140 // Simulate MAC verification failure
141 if data.is_empty() || mac.len() != 32 {
142 return Err(CryptoError::MacVerificationFailed(ERR_MAC_FAILED));
143 }
144 Ok(())
145}
146
147fn main() {
148 println!("🦆 Waddling-Errors + Thiserror Integration Demo 🦆\n");
149
150 // Example 1: Invalid salt length
151 println!("Example 1: Invalid Salt Length");
152 println!("═══════════════════════════════════════════════════");
153 let short_salt = [0u8; 16];
154 match validate_salt(&short_salt) {
155 Ok(_) => println!("✓ Salt valid"),
156 Err(e) => {
157 println!("✗ Error: {}", e);
158 println!(" Error code: E.CRYPTO.SALT.001");
159 println!(" Severity: Error");
160 }
161 }
162 println!();
163
164 // Example 2: Invalid key length
165 println!("Example 2: Invalid Key Length");
166 println!("═══════════════════════════════════════════════════");
167 let short_key = [0u8; 8];
168 match validate_key(&short_key) {
169 Ok(_) => println!("✓ Key valid"),
170 Err(e) => {
171 println!("✗ Error: {}", e);
172 println!(" Error code: E.CRYPTO.KEY.002");
173 println!(" Severity: Error");
174 }
175 }
176 println!();
177
178 // Example 3: MAC verification failed
179 println!("Example 3: MAC Verification Failed");
180 println!("═══════════════════════════════════════════════════");
181 let data = b"";
182 let mac = [0u8; 32];
183 match verify_mac(data, &mac) {
184 Ok(_) => println!("✓ MAC valid"),
185 Err(e) => {
186 println!("✗ Error: {}", e);
187 println!(" Error code: E.CRYPTO.MAC.003");
188 println!(" Severity: Error");
189 }
190 }
191 println!();
192
193 // Example 4: Demonstrating severity information
194 println!("Example 4: Severity Information");
195 println!("═══════════════════════════════════════════════════");
196 let codes = [
197 (ERR_INVALID_SALT, "Error - Invalid salt"),
198 (WARN_DEPRECATED, "Warning - Deprecated API"),
199 (CRIT_DATA_CORRUPT, "Critical - Data corruption"),
200 ];
201
202 for (code, desc) in &codes {
203 println!("Code: {} | {}", code.code(), desc);
204 println!(" Severity: {:?}", code.severity());
205 println!();
206 }
207
208 println!("Key Takeaways:");
209 println!("══════════════");
210 println!("✓ Error codes are const fn - zero runtime overhead");
211 println!("✓ Integrates cleanly with thiserror for professional errors");
212 println!("✓ Only ~500 bytes binary size overhead");
213 println!("✓ Error codes stable across versions (001, 002, 003...)");
214 println!("✓ Severity matrix enables nuanced error handling");
215 println!("\n🦆 Happy error handling! 🦆\n");
216}53fn print_error_analysis(code: &ErrorCode, description: &str) {
54 println!("╔══════════════════════════════════════════════════════════════╗");
55 println!("║ Code: {:<54} ║", code.code());
56 println!("║ Description: {:<47} ║", description);
57 println!("╠══════════════════════════════════════════════════════════════╣");
58 println!("║ Severity: {:<50} ║", format!("{:?}", code.severity()));
59 println!("║ Level: {:<53} ║", code.severity().level());
60 println!(
61 "║ Positive: {:<50} ║",
62 if code.severity().is_positive() {
63 "YES ✓"
64 } else {
65 "NO ✗"
66 }
67 );
68 println!("╚══════════════════════════════════════════════════════════════╝");
69 println!();
70}10fn main() {
11 println!("🦆 Waddling Error Sequence Conventions Demo\n");
12 println!("═══════════════════════════════════════════════════\n");
13
14 // ========================================================================
15 // CONVENTIONAL SEQUENCES (001-030)
16 // ========================================================================
17
18 println!("✅ CONVENTIONAL SEQUENCES (Recommended)\n");
19
20 // Core Errors (001-010)
21 println!("Core Errors (001-010):");
22
23 const ERR_MISSING: Code = error("CRYPTO", "SALT", 1);
24 println!(
25 " {} - .001 = MISSING (required item not provided)",
26 ERR_MISSING.code()
27 );
28
29 const ERR_MISMATCH: Code = error("CRYPTO", "LENGTH", 2);
30 println!(
31 " {} - .002 = MISMATCH (values don't match)",
32 ERR_MISMATCH.code()
33 );
34
35 const ERR_INVALID: Code = error("PATTERN", "REGEX", 3);
36 println!(
37 " {} - .003 = INVALID (format/validation failed)",
38 ERR_INVALID.code()
39 );
40
41 const ERR_OVERFLOW: Code = error("BUFFER", "SIZE", 4);
42 println!(
43 " {} - .004 = OVERFLOW (value too large)",
44 ERR_OVERFLOW.code()
45 );
46
47 const ERR_TIMEOUT: Code = blocked("NETWORK", "CONN", 7);
48 println!(
49 " {} - .007 = TIMEOUT (operation timed out)",
50 ERR_TIMEOUT.code()
51 );
52
53 const WARN_DEPRECATED: Code = warning("API", "FUNC", 10);
54 println!(
55 " {} - .010 = DEPRECATED (feature deprecated)\n",
56 WARN_DEPRECATED.code()
57 );
58
59 // State/Lifecycle Errors (011-020)
60 println!("State/Lifecycle Errors (011-020):");
61
62 const ERR_UNINITIALIZED: Code = error("ENGINE", "STATE", 11);
63 println!(
64 " {} - .011 = UNINITIALIZED (not initialized)",
65 ERR_UNINITIALIZED.code()
66 );
67
68 const ERR_ALREADYINIT: Code = error("ENGINE", "STATE", 12);
69 println!(
70 " {} - .012 = ALREADYINIT (already initialized)",
71 ERR_ALREADYINIT.code()
72 );
73
74 const ERR_CLOSED: Code = error("STREAM", "STATE", 13);
75 println!(" {} - .013 = CLOSED (resource closed)", ERR_CLOSED.code());
76
77 const BLOCKED_INPROGRESS: Code = blocked("TASK", "STATE", 15);
78 println!(
79 " {} - .015 = INPROGRESS (operation in progress)\n",
80 BLOCKED_INPROGRESS.code()
81 );
82
83 // Resource Errors (021-030)
84 println!("Resource Errors (021-030):");
85
86 const ERR_NOTFOUND: Code = error("DATA", "KEY", 21);
87 println!(
88 " {} - .021 = NOTFOUND (resource not found)",
89 ERR_NOTFOUND.code()
90 );
91
92 const ERR_ALREADYEXISTS: Code = error("FILE", "CREATE", 22);
93 println!(
94 " {} - .022 = ALREADYEXISTS (already exists)",
95 ERR_ALREADYEXISTS.code()
96 );
97
98 const CRIT_EXHAUSTED: Code = critical("MEM", "ALLOC", 23);
99 println!(
100 " {} - .023 = EXHAUSTED (resource exhausted)",
101 CRIT_EXHAUSTED.code()
102 );
103
104 const BLOCKED_LOCKED: Code = blocked("THREAD", "MUTEX", 24);
105 println!(
106 " {} - .024 = LOCKED (resource locked)",
107 BLOCKED_LOCKED.code()
108 );
109
110 const CRIT_CORRUPTED: Code = critical("CRYPTO", "MAC", 25);
111 println!(
112 " {} - .025 = CORRUPTED (data corrupted)\n",
113 CRIT_CORRUPTED.code()
114 );
115
116 // ========================================================================
117 // PROJECT-SPECIFIC SEQUENCES (031-897)
118 // ========================================================================
119
120 println!("═══════════════════════════════════════════════════\n");
121 println!("✨ PROJECT-SPECIFIC SEQUENCES (Free Use)\n");
122 println!("Domain-Specific Range (031-897):");
123
124 const ERR_HMAC_COMPUTE: Code = error("CRYPTO", "HMAC", 31);
125 println!(
126 " {} - Domain-specific (HMAC computation)",
127 ERR_HMAC_COMPUTE.code()
128 );
129
130 const ERR_PATTERN_COMPLEX: Code = warning("PATTERN", "PERF", 45);
131 println!(
132 " {} - Domain-specific (pattern complexity)",
133 ERR_PATTERN_COMPLEX.code()
134 );
135
136 const ERR_AST_MALFORMED: Code = error("parser", "AST", 51);
137 println!(
138 " {} - Domain-specific (AST structure)\n",
139 ERR_AST_MALFORMED.code()
140 );
141
142 // ========================================================================
143 // SUCCESS SEQUENCES (998-999)
144 // ========================================================================
145
146 println!("═══════════════════════════════════════════════════\n");
147 println!("🎉 SUCCESS SEQUENCES (Positive Outcomes)\n");
148 println!("Success Range (998-999):");
149
150 const SUCCESS_PARTIAL: Code = success("BUILD", "RESULT", 998);
151 println!(
152 " {} - .998 = PARTIAL (partial success)",
153 SUCCESS_PARTIAL.code()
154 );
155
156 const SUCCESS_COMPLETE: Code = success("REDACT", "DONE", 999);
157 println!(
158 " {} - .999 = COMPLETE (full completion)",
159 SUCCESS_COMPLETE.code()
160 );
161
162 const COMPLETE_COMPILE: Code = completed("BUILD", "DONE", 999);
163 println!(
164 " {} - .999 = COMPLETE (compilation finished)\n",
165 COMPLETE_COMPILE.code()
166 );
167
168 // ========================================================================
169 // CROSS-PROJECT CONSISTENCY
170 // ========================================================================
171
172 println!("═══════════════════════════════════════════════════\n");
173 println!("🌐 CROSS-PROJECT CONSISTENCY\n");
174 println!("Same semantic meaning across different projects:\n");
175
176 // "Missing" errors across different projects
177 const DUCOY_MISSING: Code = error("CRYPTO", "SALT", 1);
178 println!("Ducoy: {} (.001 = MISSING)", DUCOY_MISSING.code());
179
180 const QUACKPATCH_MISSING: Code = error("parser", "TOKEN", 1);
181 println!("QuackPatch: {} (.001 = MISSING)", QUACKPATCH_MISSING.code());
182
183 const STATEQUACK_MISSING: Code = error("STATE", "KEY", 1);
184 println!(
185 "StateQuack: {} (.001 = MISSING)\n",
186 STATEQUACK_MISSING.code()
187 );
188
189 println!("👆 Notice: .001 ALWAYS means \"missing\" - instant recognition!\n");
190
191 // ========================================================================
192 // BENEFITS
193 // ========================================================================
194
195 println!("═══════════════════════════════════════════════════\n");
196 println!("💡 BENEFITS OF CONVENTIONS\n");
197 println!(" ✅ Instant Recognition");
198 println!(" .001 anywhere → \"missing\" error\n");
199 println!(" ✅ Cross-Project Learning");
200 println!(" Understand Ducoy → understand all Waddling projects\n");
201 println!(" ✅ Searchability");
202 println!(" Search .001 finds all \"missing\" errors ecosystem-wide\n");
203 println!(" ✅ Predictability");
204 println!(" Users can guess meanings from sequences alone\n");
205 println!(" ✅ Documentation");
206 println!(" Document patterns once, reference everywhere\n");
207
208 println!("═══════════════════════════════════════════════════\n");
209 println!("📚 Full documentation: docs/SEQUENCE-CONVENTIONS.md");
210 println!("🔧 Enforcement strategies: docs/ENFORCEMENT.md\n");
211}Sourcepub fn write_code(&self, f: &mut impl Write) -> Result
pub fn write_code(&self, f: &mut impl Write) -> Result
Write error code to formatter without allocating (e.g., “E.CRYPTO.SALT.001”)
Use this in performance-critical paths to avoid String allocation.
§Examples
use waddling_errors::{ErrorCode, Severity};
use std::fmt::Write;
let code = ErrorCode::new(Severity::Error, "CRYPTO", "SALT", 1);
let mut buf = String::new();
code.write_code(&mut buf).unwrap();
assert_eq!(buf, "E.CRYPTO.SALT.001");Sourcepub const fn severity(&self) -> Severity
pub const fn severity(&self) -> Severity
Get severity (e.g., Severity::Error)
Examples found in repository?
53fn print_error_analysis(code: &ErrorCode, description: &str) {
54 println!("╔══════════════════════════════════════════════════════════════╗");
55 println!("║ Code: {:<54} ║", code.code());
56 println!("║ Description: {:<47} ║", description);
57 println!("╠══════════════════════════════════════════════════════════════╣");
58 println!("║ Severity: {:<50} ║", format!("{:?}", code.severity()));
59 println!("║ Level: {:<53} ║", code.severity().level());
60 println!(
61 "║ Positive: {:<50} ║",
62 if code.severity().is_positive() {
63 "YES ✓"
64 } else {
65 "NO ✗"
66 }
67 );
68 println!("╚══════════════════════════════════════════════════════════════╝");
69 println!();
70}More examples
147fn main() {
148 println!("🦆 Waddling-Errors + Thiserror Integration Demo 🦆\n");
149
150 // Example 1: Invalid salt length
151 println!("Example 1: Invalid Salt Length");
152 println!("═══════════════════════════════════════════════════");
153 let short_salt = [0u8; 16];
154 match validate_salt(&short_salt) {
155 Ok(_) => println!("✓ Salt valid"),
156 Err(e) => {
157 println!("✗ Error: {}", e);
158 println!(" Error code: E.CRYPTO.SALT.001");
159 println!(" Severity: Error");
160 }
161 }
162 println!();
163
164 // Example 2: Invalid key length
165 println!("Example 2: Invalid Key Length");
166 println!("═══════════════════════════════════════════════════");
167 let short_key = [0u8; 8];
168 match validate_key(&short_key) {
169 Ok(_) => println!("✓ Key valid"),
170 Err(e) => {
171 println!("✗ Error: {}", e);
172 println!(" Error code: E.CRYPTO.KEY.002");
173 println!(" Severity: Error");
174 }
175 }
176 println!();
177
178 // Example 3: MAC verification failed
179 println!("Example 3: MAC Verification Failed");
180 println!("═══════════════════════════════════════════════════");
181 let data = b"";
182 let mac = [0u8; 32];
183 match verify_mac(data, &mac) {
184 Ok(_) => println!("✓ MAC valid"),
185 Err(e) => {
186 println!("✗ Error: {}", e);
187 println!(" Error code: E.CRYPTO.MAC.003");
188 println!(" Severity: Error");
189 }
190 }
191 println!();
192
193 // Example 4: Demonstrating severity information
194 println!("Example 4: Severity Information");
195 println!("═══════════════════════════════════════════════════");
196 let codes = [
197 (ERR_INVALID_SALT, "Error - Invalid salt"),
198 (WARN_DEPRECATED, "Warning - Deprecated API"),
199 (CRIT_DATA_CORRUPT, "Critical - Data corruption"),
200 ];
201
202 for (code, desc) in &codes {
203 println!("Code: {} | {}", code.code(), desc);
204 println!(" Severity: {:?}", code.severity());
205 println!();
206 }
207
208 println!("Key Takeaways:");
209 println!("══════════════");
210 println!("✓ Error codes are const fn - zero runtime overhead");
211 println!("✓ Integrates cleanly with thiserror for professional errors");
212 println!("✓ Only ~500 bytes binary size overhead");
213 println!("✓ Error codes stable across versions (001, 002, 003...)");
214 println!("✓ Severity matrix enables nuanced error handling");
215 println!("\n🦆 Happy error handling! 🦆\n");
216}100fn main() {
101 println!("🦆 Waddling-Errors Standalone Demo 🦆\n");
102 println!("Zero external dependencies - just pure error codes!\n");
103
104 // Example 1: Custom error type
105 println!("═══════════════════════════════════════════════════");
106 println!("Example 1: Custom Error Type with ErrorCode");
107 println!("═══════════════════════════════════════════════════");
108
109 match validate_age(-5) {
110 Ok(_) => println!("✓ Age valid"),
111 Err(e) => {
112 println!("✗ Error: {}", e);
113 println!(" Code: {}", e.code().code());
114 println!(" Severity: {:?}", e.code().severity());
115 }
116 }
117 println!();
118
119 // Example 2: Not found error
120 println!("═══════════════════════════════════════════════════");
121 println!("Example 2: Data Not Found");
122 println!("═══════════════════════════════════════════════════");
123
124 match find_user(0) {
125 Ok(user) => println!("✓ Found: {}", user),
126 Err(e) => {
127 println!("✗ Error: {}", e);
128 println!(" Code: {}", e.code().code());
129 }
130 }
131 println!();
132
133 // Example 3: Warnings
134 println!("═══════════════════════════════════════════════════");
135 println!("Example 3: Warnings");
136 println!("═══════════════════════════════════════════════════");
137
138 match process_with_warnings("old_api_call()") {
139 Ok(result) => println!("✓ Processed (with warnings): {}", result),
140 Err(e) => println!("✗ Failed: {}", e),
141 }
142 println!();
143
144 // Example 4: Direct ErrorCode returns (ultra minimal)
145 println!("═══════════════════════════════════════════════════");
146 println!("Example 4: Direct ErrorCode Returns (Ultra Minimal)");
147 println!("═══════════════════════════════════════════════════");
148
149 match quick_validate(-10) {
150 Ok(val) => println!("✓ Result: {}", val),
151 Err(code) => {
152 println!("✗ Failed with code: {}", code.code());
153 println!(" Just the error code - no wrapper type needed!");
154 }
155 }
156 println!();
157
158 // Example 5: Success codes
159 println!("═══════════════════════════════════════════════════");
160 println!("Example 5: Success Codes (Active Diagnostic Systems)");
161 println!("═══════════════════════════════════════════════════");
162
163 println!("Task completed!");
164 println!(" Code: {}", SUCCESS_COMPLETE.code());
165 println!(" Positive: {}", SUCCESS_COMPLETE.severity().is_positive());
166 println!(" Active systems can celebrate success! 🎉");
167 println!();
168
169 // Summary
170 println!("═══════════════════════════════════════════════════");
171 println!("Key Takeaways");
172 println!("═══════════════════════════════════════════════════");
173 println!("✓ No external dependencies (thiserror/anyhow optional)");
174 println!("✓ Error codes are const fn (zero runtime cost)");
175 println!("✓ Works in no_std environments");
176 println!("✓ ~500 bytes binary size overhead");
177 println!("✓ DIY error types or direct ErrorCode returns");
178 println!("✓ Full control over error handling");
179 println!("\n🦆 Pure, lightweight, flexible! 🦆\n");
180}