[go: up one dir, main page]

Module error

Module error 

Source
Expand description

§Error Handling for CCXT Rust

This module provides a comprehensive, production-grade error handling system for the ccxt-rust library. It is designed following Rust community best practices and the principles outlined in the Error Handling Project Group.

§Design Philosophy

The error handling system is built around these core principles:

  1. Type Safety: Strongly-typed errors using thiserror for compile-time guarantees
  2. API Stability: All public enums use #[non_exhaustive] for forward compatibility
  3. Zero Panic: No unwrap() or expect() on recoverable error paths
  4. Context Rich: Full error chain support with context attachment
  5. Performance: Optimized memory layout using Cow<'static, str> and Box
  6. Thread Safety: All error types implement Send + Sync + 'static
  7. Observability: Integration with tracing for structured logging

§Error Hierarchy

Error (main error type)
├── Exchange      - Exchange-specific API errors
├── Network       - Network/transport layer errors (via NetworkError)
├── Parse         - Response parsing errors (via ParseError)
├── Order         - Order management errors (via OrderError)
├── Authentication - API key/signature errors
├── RateLimit     - Rate limiting with retry information
├── Timeout       - Operation timeout
├── InvalidRequest - Invalid parameters
├── MarketNotFound - Unknown trading pair
├── WebSocket     - WebSocket communication errors
└── Context       - Error with additional context

§Quick Start

§Basic Error Handling

use ccxt_core::error::{Error, Result};

fn fetch_price(symbol: &str) -> Result<f64> {
    if symbol.is_empty() {
        return Err(Error::invalid_request("Symbol cannot be empty"));
    }
    // ... fetch price logic
    Ok(42000.0)
}

§Adding Context to Errors

use ccxt_core::error::{Error, Result, ContextExt};

fn process_order(order_id: &str) -> Result<()> {
    validate_order(order_id)
        .context("Failed to validate order")?;
     
    submit_order(order_id)
        .with_context(|| format!("Failed to submit order {}", order_id))?;
     
    Ok(())
}

§Handling Specific Error Types

use ccxt_core::error::{Error, NetworkError};

fn handle_error(err: Error) {
    // Check if error is retryable
    if err.is_retryable() {
        if let Some(duration) = err.retry_after() {
            println!("Retry after {:?}", duration);
        }
    }
     
    // Check for specific error types through context layers
    if let Some(msg) = err.as_authentication() {
        println!("Auth error: {}", msg);
    }
     
    // Get full error report
    println!("Error report:\n{}", err.report());
}

§Creating Exchange Errors

use ccxt_core::error::Error;

// Simple exchange error
let err = Error::exchange("-1121", "Invalid symbol");

// Exchange error with raw response data
let err = Error::exchange_with_data(
    "400",
    "Bad Request",
    serde_json::json!({"code": -1121, "msg": "Invalid symbol"})
);

§Memory Optimization

The Error enum is optimized to be ≤56 bytes on 64-bit systems:

  • Large variants (Exchange, Network, Parse, Order, WebSocket, Context) are boxed to keep the enum size small
  • String fields use Cow<'static, str> to avoid allocation for static strings
  • Use Error::authentication("static message") for zero-allocation errors
  • Use Error::authentication(format!("dynamic {}", value)) when needed

§Feature Flags

  • backtrace: Enable backtrace capture in ExchangeErrorDetails for debugging

§Integration with anyhow

For application-level code, errors can be converted to anyhow::Error:

use ccxt_core::error::Error;

fn app_main() -> anyhow::Result<()> {
    let result: Result<(), Error> = Err(Error::timeout("Operation timed out"));
    result?; // Automatically converts to anyhow::Error
    Ok(())
}

Structs§

ExchangeErrorDetails
Details for exchange-specific errors.

Enums§

Error
The primary error type for the ccxt-rust library.
NetworkError
Encapsulated network errors hiding implementation details.
OrderError
Errors related to order management operations.
ParseError
Errors related to parsing exchange responses.

Traits§

ContextExt
Extension trait for ergonomic error context attachment.
ErrorContextDeprecated
Helper trait for adding context to errors (legacy alias for ContextExt).

Type Aliases§

Result
Result type alias for all CCXT operations.