waddling-errors 0.7.3

Structured, secure-by-default diagnostic codes for distributed systems with no_std and role-based documentation
Documentation
# Waddling-Errors Quick Reference

**Version**: 0.7.x

---

## Installation

```toml
# Default (no_std + alloc)
waddling-errors = "0.7"

# With all features
waddling-errors = { version = "0.7", features = ["std", "doc-gen", "hash", "serde"] }

# Pure no_std
waddling-errors = { version = "0.7", default-features = false }
```

---

## Basic Setup

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

// 1. Define components
#[derive(Debug, Copy, Clone)]
enum Component { Auth, Database }

impl ComponentId for Component {
    fn as_str(&self) -> &'static str {
        match self { Component::Auth => "AUTH", Component::Database => "DB" }
    }
}

// 2. Define primaries
#[derive(Debug, Copy, Clone)]
enum Primary { Token, Connection }

impl PrimaryId for Primary {
    fn as_str(&self) -> &'static str {
        match self { Primary::Token => "TOKEN", Primary::Connection => "CONN" }
    }
}

// 3. Create error codes
const ERR_TOKEN_MISSING: Code<Component, Primary> = 
    error(Component::Auth, Primary::Token, 1);
```

---

## Constructor Functions

```rust
error(component, primary, seq)      // E - Error
warning(component, primary, seq)    // W - Warning
critical(component, primary, seq)   // C - Critical
blocked(component, primary, seq)    // B - Blocked
success(component, primary, seq)    // S - Success
completed(component, primary, seq)  // K - Completed
info(component, primary, seq)       // I - Info
trace(component, primary, seq)      // T - Trace
help(component, primary, seq)       // H - Help
```

---

## Code Methods

```rust
let code = ERR_TOKEN_MISSING;

code.code()           // "E.AUTH.TOKEN.001"
code.severity()       // Severity::Error
code.component()      // Component::Auth
code.component_str()  // "AUTH"
code.primary()        // Primary::Token
code.primary_str()    // "TOKEN"
code.sequence()       // 1
code.write_code(&mut buf) // Write without allocating

// With hash feature
code.hash()           // "jGKFp" (5-char base62)
```

---

## Severity Methods

```rust
let sev = Severity::Error;

sev.as_char()         // 'E'
sev.as_str()          // "Error"
sev.description()     // "Operation failed"
sev.priority()        // 8 (0-8 scale)
sev.is_blocking()     // true
sev.is_negative()     // true
sev.is_positive()     // false
sev.is_neutral()      // false

// With features
sev.emoji()           // "❌" (requires "emoji")
sev.ansi_color()      // "\x1b[1;31m" (requires "ansi-colors")
```

---

## Severity Levels

| Code | Name | Priority | Blocking | Use |
|------|------|----------|----------|-----|
| `E` | Error | 8 || Operation failed |
| `B` | Blocked | 7 || Waiting/blocked |
| `C` | Critical | 6 || Severe issue |
| `W` | Warning | 5 || Potential issue |
| `H` | Help | 4 || Suggestion |
| `S` | Success | 3 || Succeeded |
| `K` | Completed | 2 || Task done |
| `I` | Info | 1 || Information |
| `T` | Trace | 0 || Debug trace |

---

## Sequence Conventions

| Seq | Meaning | Example |
|-----|---------|---------|
| 001 | MISSING | Required item not provided |
| 002 | MISMATCH | Type/length mismatch |
| 003 | INVALID | Validation failed |
| 007 | DUPLICATE | Duplicate entry |
| 008 | DENIED | Permission denied |
| 017 | TIMEOUT | Operation timed out |
| 021 | NOTFOUND | Resource not found |
| 025 | CORRUPTED | Data corruption |
| 999 | COMPLETE | Full completion |

See [SEQUENCE-CONVENTIONS.md](SEQUENCE-CONVENTIONS.md) for full list.

---

## Usage Patterns

### In Result Types

```rust
type AppResult<T> = Result<T, Code<Component, Primary>>;

fn authenticate(token: Option<&str>) -> AppResult<String> {
    token.ok_or(ERR_TOKEN_MISSING)?;
    Ok("user123".to_string())
}
```

### Pattern Matching

```rust
match code.component() {
    Component::Auth => handle_auth_error(code),
    Component::Database => handle_db_error(code),
}
```

### Priority Handling

```rust
match code.severity().priority() {
    8 => { /* Error - stop */ }
    7 => { /* Blocked - retry */ }
    5..=6 => { /* Warning/Critical - log */ }
    _ => { /* Info/Success */ }
}
```

---

## Feature Flags

| Feature | Adds | Use Case |
|---------|------|----------|
| `macros` | Proc macros | Less boilerplate (default) |
| `std` | Standard lib | File I/O, doc generation |
| `hash` | Base62 hashes | Compact logging |
| `emoji` | Unicode emoji | Visual output |
| `ansi-colors` | Color codes | Colored logs |
| `serde` | Serialization | JSON APIs |
| `doc-gen` | HTML/JSON docs | Auto-documentation |
| `metadata` | Compile metadata | Doc generation |

---

## Common Patterns

### Error Module

```rust
// src/errors.rs
pub use waddling_errors::prelude::*;

pub type AppCode = Code<Component, Primary>;
pub type AppResult<T> = Result<T, AppCode>;

// Auth errors
pub const ERR_TOKEN_MISSING: AppCode = error(Component::Auth, Primary::Token, 1);
pub const ERR_TOKEN_INVALID: AppCode = error(Component::Auth, Primary::Token, 3);

// DB errors
pub const ERR_DB_TIMEOUT: AppCode = error(Component::Database, Primary::Connection, 17);
```

### With thiserror

```rust
use thiserror::Error;

#[derive(Error, Debug)]
pub enum AppError {
    #[error("{0}: {1}")]
    Auth(String, String),
}

impl AppError {
    fn from_code(code: AppCode, msg: &str) -> Self {
        AppError::Auth(code.code(), msg.to_string())
    }
}
```

### Custom Display

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

---

## Examples

```bash
# Basic usage
cargo run --example trait_based_enums

# Full system
cargo run --example complete_system --features "doc-gen,hash,metadata"

# Integration patterns
cargo run --example integration_with_error_handling

# no_std
cargo run --example no_std_example
cargo build --example wasm_minimal --target wasm32-unknown-unknown --no-default-features
```

---

## Documentation Generation

```rust
use waddling_errors::doc_generator::{DocRegistry, HtmlRenderer, JsonRenderer};

let mut registry = DocRegistry::new("My App", "1.0.0");

registry.register_component("AUTH", Some("Authentication"), &[], &["security"])?;
registry.register_code_extended(
    &ERR_TOKEN_MISSING,
    "Token missing",
    &["Add Authorization header"],
    &["auth"],
    Some(Role::Public),
    &[], None, &[],
)?;

registry.render_all_roles(
    vec![Box::new(JsonRenderer), Box::new(HtmlRenderer::new())],
    "target/docs"
)?;
```

---

## Troubleshooting

```rust
// ❌ Sequence > 999
const ERR: AppCode = error(Component::Auth, Primary::Token, 1000);
// ✅ Use 001-999
const ERR: AppCode = error(Component::Auth, Primary::Token, 999);

// ❌ Missing hash method
let h = code.hash();
// ✅ Enable feature
// Cargo.toml: features = ["hash"]

// ❌ no_std errors with std features
waddling-errors = "0.7"
// ✅ Disable default features
waddling-errors = { version = "0.7", default-features = false }
```

---

## Links

- [Full Usage Guide]USAGE_GUIDE.md
- [API Docs]https://docs.rs/waddling-errors
- [Sequence Conventions]SEQUENCE-CONVENTIONS.md
- [Feature Flags]FEATURE_FLAGS.md
- [Doc Generation]DOC_GENERATION_GUIDE.md