Module error

Module error 

Source
Expand description

Error types and result handling for WsForge.

This module provides a unified error type that covers all possible error conditions in the WsForge framework, from WebSocket protocol errors to application-level errors.

§Overview

The error handling in WsForge is designed to be:

  • Ergonomic: Using Result<T> as a type alias for std::result::Result<T, Error>
  • Informative: Each variant provides context about what went wrong
  • Composable: Implements From traits for automatic error conversion
  • Debuggable: All errors implement Display and Debug for easy troubleshooting

§Error Categories

Errors are organized into several categories:

  • Protocol Errors: WebSocket and IO errors
  • Serialization Errors: JSON parsing and serialization failures
  • Framework Errors: Connection and routing issues
  • Application Errors: Custom business logic errors

§Examples

§Basic Error Handling

use wsforge::prelude::*;

async fn handler(msg: Message) -> Result<String> {
    // Automatic error conversion from serde_json::Error
    let data: serde_json::Value = msg.json()?;

    // Create custom error
    if data.is_null() {
        return Err(Error::custom("Data cannot be null"));
    }

    Ok("Success".to_string())
}

§Pattern Matching on Errors

use wsforge::prelude::*;

match result {
    Ok(_) => println!("Success!"),
    Err(Error::ConnectionNotFound(id)) => {
        eprintln!("Connection {} not found", id);
    }
    Err(Error::Json(e)) => {
        eprintln!("JSON error: {}", e);
    }
    Err(e) => {
        eprintln!("Other error: {}", e);
    }
}

§Creating Custom Errors

use wsforge::prelude::*;

async fn validate_user(username: &str) -> Result<()> {
    if username.is_empty() {
        return Err(Error::custom("Username cannot be empty"));
    }

    if username.len() < 3 {
        return Err(Error::handler(
            format!("Username '{}' is too short (minimum 3 characters)", username)
        ));
    }

    Ok(())
}

Enums§

Error
The main error type for WsForge operations.

Type Aliases§

Result
A type alias for Result<T, Error>.