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:
- Type Safety: Strongly-typed errors using
thiserrorfor compile-time guarantees - API Stability: All public enums use
#[non_exhaustive]for forward compatibility - Zero Panic: No
unwrap()orexpect()on recoverable error paths - Context Rich: Full error chain support with context attachment
- Performance: Optimized memory layout using
Cow<'static, str>andBox - Thread Safety: All error types implement
Send + Sync + 'static - Observability: Integration with
tracingfor 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 inExchangeErrorDetailsfor 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§
- Exchange
Error Details - Details for exchange-specific errors.
Enums§
- Error
- The primary error type for the
ccxt-rustlibrary. - Network
Error - Encapsulated network errors hiding implementation details.
- Order
Error - Errors related to order management operations.
- Parse
Error - Errors related to parsing exchange responses.
Traits§
- Context
Ext - Extension trait for ergonomic error context attachment.
- Error
Context Deprecated - Helper trait for adding context to errors (legacy alias for ContextExt).
Type Aliases§
- Result
- Result type alias for all CCXT operations.