waddling-errors 0.2.0

Ultra-minimal error code standard for the Waddling ecosystem
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
# waddling-errors đŸĻ†

**Ultra-minimal diagnostic code system**

[![Crates.io](https://img.shields.io/crates/v/waddling-errors.svg)](https://crates.io/crates/waddling-errors)
[![Documentation](https://docs.rs/waddling-errors/badge.svg)](https://docs.rs/waddling-errors)
[![License](https://img.shields.io/crates/l/waddling-errors.svg)](LICENSE)

---

## Overview

`waddling-errors` provides a **super ergonomic diagnostic code system** with consistent error code format generation.

### Key Features

- ✅ **Tiny** - Modular design, only include what you need
- ✅ **Zero dependencies by default** - Optional features for extended functionality
- ✅ **Semantic methods** - `is_blocking()`, `is_positive()`, `priority()`, etc.
- ✅ **Visual representation** - Emojis (đŸ”Ĩâš ī¸âœ…) and ANSI colors for terminal UIs
- ✅ **Serialization** - Optional Serde support for JSON/etc.
- ✅ **`no_std` compatible** - Works in embedded and WASM environments
- ✅ **Const-friendly** - Error codes can be defined as constants

---

## Why This Exists

Projects need **consistent error code formats** for diagnostic tooling integration.

### Standard Format

**4-Part Format** - consistent diagnostic codes:
```
SEVERITY.COMPONENT.PRIMARY.SEQUENCE → E.CRYPTO.SALT.001
```

Where SEVERITY can be:

| Severity     | Code | Emoji | Use Case                          |
|--------------|------|-------|-----------------------------------|
| **Error**    | `E`  | ❌    | Invalid input, logic errors       |
| **Warning**  | `W`  | âš ī¸    | Deprecated API, edge cases        |
| **Critical** | `C`  | đŸ”Ĩ    | Data corruption, security breach  |
| **Blocked**  | `B`  | đŸšĢ    | Deadlock, I/O wait, network down  |
| **Success**  | `S`  | ✅    | Operation succeeded               |
| **Completed**| `K`  | âœ”ī¸    | Task/phase finished               |
| **Info**     | `I`  | â„šī¸    | Events, milestones, status        |
| **Trace**    | `T`  | 🔍    | Execution traces, probes, timing  |

**Solution:** `waddling-errors` provides a **single, minimal, flexible** implementation.

---

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
# Minimal (no optional features)
waddling-errors = { version = "0.1", default-features = false }

# With base62 hashing
waddling-errors = { version = "0.1", features = ["hash"] }

# With ANSI terminal colors
waddling-errors = { version = "0.1", features = ["ansi-colors"] }

# With emoji support
waddling-errors = { version = "0.1", features = ["emoji"] }

# With Serde serialization
waddling-errors = { version = "0.1", features = ["serde"] }

# All features
waddling-errors = { version = "0.1", features = ["hash", "ansi-colors", "emoji", "serde"] }
```

---

## Quick Start

```rust
use waddling_errors::prelude::*;

// Ultra-clean error definitions
const ERR_SALT: Code = error("CRYPTO", "SALT", 1);
const WARN_DEPRECATED: Code = warning("API", "FUNC", 10);
const SUCCESS_BUILD: Code = success("BUILD", "DONE", 999);

fn validate(data: &[u8]) -> Result<(), Code> {
    if data.is_empty() {
        return Err(ERR_SALT);
    }
    Ok(())
}

fn main() {
    println!("{}", ERR_SALT.code()); // "E.CRYPTO.SALT.001"
    
    // Semantic methods
    println!("Is blocking? {}", ERR_SALT.severity().is_blocking()); // true
    println!("Priority: {}", ERR_SALT.severity().priority()); // 7 (highest)
    
    // Visual representation
    println!("{} Error occurred!", ERR_SALT.severity().emoji()); // "❌ Error occurred!"
}
```

---

## Usage Patterns

waddling-errors provides **multiple API styles** - choose what fits your project:

### 1. Convenience Functions (Recommended)

The cleanest, most ergonomic approach:

```rust
use waddling_errors::prelude::*;

// All 8 severity levels
const ERR: Code = error("CRYPTO", "SALT", 1);
const WARN: Code = warning("API", "FUNC", 10);
const CRIT: Code = critical("MEM", "CORRUPT", 23);
const BLOCK: Code = blocked("THREAD", "LOCK", 24);
const SUCCESS: Code = success("BUILD", "DONE", 999);
const COMPLETE: Code = completed("PARSE", "DONE", 999);
const INFO: Code = info("SERVER", "START", 1);
const TRACE: Code = trace("PROBE", "THREAD", 1);
```

### 2. Method Style

Object-oriented approach:

```rust
use waddling_errors::Code;

const ERR: Code = Code::error("CRYPTO", "SALT", 1);
const WARN: Code = Code::warning("API", "FUNC", 10);
```

### 3. Explicit Severity

Full control when needed:

```rust
use waddling_errors::{Code, Severity};

const ERR: Code = Code::new(Severity::Error, "CRYPTO", "SALT", 1);
```

### Standalone Usage (No Dependencies)

Return diagnostic codes directly:

```rust
use waddling_errors::prelude::*;

const ERR_INVALID_SALT: Code = error("CRYPTO", "SALT", 1);

fn validate(data: &[u8]) -> Result<(), Code> {
    if data.is_empty() {
        return Err(ERR_INVALID_SALT);
    }
    Ok(())
}

// Or wrap in your own error type
#[derive(Debug)]
struct MyError {
    code: Code,
    message: String,
}

impl std::fmt::Display for MyError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "[MYAPP.{}] {}", self.code.code(), self.message)
    }
}
```

See `examples/standalone.rs` for a complete example with no external dependencies.

---

### Error Registry Pattern (Recommended)

For larger projects, create a central error registry:

```rust
// errors.rs - Your project's error registry
pub mod errors {
    use waddling_errors::prelude::*;
    
    // Crypto errors (E.CRYPTO.*)
    pub const SALT_MISSING: Code = error("CRYPTO", "SALT", 1);
    pub const KEY_LENGTH: Code = error("CRYPTO", "LENGTH", 2);
    pub const HMAC_INVALID: Code = error("CRYPTO", "HMAC", 3);
    
    // Parser warnings (W.PARSE.*)
    pub const DEPRECATED_SYNTAX: Code = warning("PARSE", "DEPR", 1);
    
    // Build success (S.BUILD.*)
    pub const BUILD_COMPLETE: Code = success("BUILD", "DONE", 999);
}

// Use across your project
use errors::SALT_MISSING;

fn validate_salt(salt: &[u8]) -> Result<(), Code> {
    if salt.len() != 32 {
        return Err(SALT_MISSING);
    }
    Ok(())
}
```

**Benefits:**
- ✅ Centralized error definitions
- ✅ Easy to document and maintain
- ✅ Prevents duplicate sequence numbers
- ✅ IDE autocomplete for all error codes

---

## Semantic Methods

`Severity` provides rich semantic methods for intelligent error handling:

### Categorization

```rust
use waddling_errors::Severity;

// Check if execution should stop
if severity.is_blocking() {
    return Err(diagnostic);  // Error or Blocked
}

// Categorize outcomes
if severity.is_positive() {
    println!("✅ Success!");  // Success or Completed
} else if severity.is_negative() {
    println!("âš ī¸ Issue detected");  // Error, Warning, Critical, Blocked
} else {
    println!("â„šī¸ Info");  // Info or Trace
}
```

### Priority Ordering

```rust
use waddling_errors::Severity;

// Sort diagnostics by priority (0=lowest, 7=highest)
diagnostics.sort_by_key(|d| d.severity.priority());

// Filter by severity level
let critical_issues: Vec<_> = diagnostics
    .iter()
    .filter(|d| d.severity >= Severity::Warning)
    .collect();
```

### Metadata

```rust
use waddling_errors::Severity;

let sev = Severity::Error;
println!("Char: {}", sev.as_char());        // "E"
println!("Name: {}", sev.as_str());         // "Error"
println!("Desc: {}", sev.description());    // "Operation failed"
println!("Priority: {}", sev.priority());   // 7
```

---

## Visual Representation

### Emojis (Feature Flag)

Perfect for modern terminal UIs and logs (requires `emoji` feature):

```rust
use waddling_errors::prelude::*;

println!("{} Build failed!", error("BUILD", "FAIL", 1).severity().emoji());
// Output: ❌ Build failed!

println!("{} Warning: deprecated API", warning("API", "DEPR", 1).severity().emoji());
// Output: âš ī¸ Warning: deprecated API

println!("{} All tests passed!", success("TEST", "PASS", 1).severity().emoji());
// Output: ✅ All tests passed!
```

**Full emoji set:**
- ❌ Error
- đŸšĢ Blocked
- đŸ”Ĩ Critical (stands out from warning!)
- âš ī¸ Warning
- ✅ Success
- âœ”ī¸ Completed
- â„šī¸ Info
- 🔍 Trace

### ANSI Colors (Feature Flag)

Enable with `features = ["ansi-colors"]`:

```rust
use waddling_errors::Severity;

let severity = Severity::Error;
println!(
    "{}Error: Operation failed{}",
    severity.ansi_color(),
    Severity::ANSI_RESET
);
// Output: Error in bold red

// Combine with emojis for maximum clarity
println!(
    "{}{} {}{}",
    severity.ansi_color(),
    severity.emoji(),
    "Critical failure",
    Severity::ANSI_RESET
);
// Output: ❌ Critical failure (in red)
```

---

## Serialization

Enable with `features = ["serde"]`:

```rust
use waddling_errors::prelude::*;
use serde_json;

let codes = vec![
    error("CRYPTO", "SALT", 1),
    warning("API", "DEPR", 10),
];

// Serialize to JSON
let json = serde_json::to_string(&codes)?;
// [{"severity":"Error","component":"CRYPTO","primary":"SALT","sequence":1}, ...]

// Severities support full round-trip
let severity = Severity::Error;
let json = serde_json::to_string(&severity)?;
let restored: Severity = serde_json::from_str(&json)?;
```

---

## Sequence Conventions

The Waddling ecosystem uses **semantic sequence numbers** for common patterns:

| Sequence | Meaning    | Example                           |
|----------|------------|-----------------------------------|
| 001      | MISSING    | Required item not provided        |
| 002      | MISMATCH   | Values don't match expected type  |
| 003      | INVALID    | Format/validation failed          |
| 021      | NOTFOUND   | Resource not found                |
| 025      | CORRUPTED  | Data corruption detected          |
| 031-897  | (project)  | Domain-specific sequences         |
| 999      | COMPLETE   | Full completion                   |

**Benefits:** `.001` always means "missing" across ALL Waddling projects.

See `docs/SEQUENCE-CONVENTIONS.md` for the complete list.

---

## Examples

Run the examples to see features in action:

```bash
# Basic emoji support
cargo run --example emoji_demo --features emoji

# ANSI colored terminal output
cargo run --example ansi_colors_demo --features ansi-colors

# Serde serialization
cargo run --example serde_demo --features serde

# Complete severity matrix
cargo run --example severity_matrix
```

---

## Documentation

- **[CHANGELOG.md]CHANGELOG.md** - Version history and release notes
- **[docs/FEATURE_FLAGS.md]docs/FEATURE_FLAGS.md** - Comprehensive feature guide
- **[API Documentation]https://docs.rs/waddling-errors** - Full API reference on docs.rs

---

## License

Dual-licensed under MIT or Apache-2.0.