Crate yoshi_std

Source
Expand description

Brief: Comprehensive error handling framework for robust Rust applications.

Yoshi provides structured error types with rich contextual information, making it easier to debug, trace, and handle errors throughout your application. It offers flexible error categorization, context chaining, and optional backtrace capture while maintaining excellent performance characteristics.

Module Classification: Performance-Critical
Complexity Level: Expert
API Stability: Stable

§Key Features

Structured Error Types: Define precise error categories with relevant metadata rather than relying on string-based errors. Each error kind captures the specific information needed for that failure mode.

Rich Context: Add diagnostic information, suggestions, and typed payloads as errors propagate through your application. Context is preserved without performance overhead.

Performance Focused: Sub-microsecond error creation with O(1) context attachment. Backtrace capture is conditional and can be disabled in production.

no_std Compatible: Full functionality available in no_std environments with automatic fallbacks for platform-specific features.

§Usage Patterns

Yoshi works well for applications that need detailed error diagnostics and structured error handling. It’s particularly useful when you want to:

  • Provide rich debugging information to developers
  • Maintain error context across call stacks
  • Categorize errors for different handling strategies
  • Include suggestions and metadata for error recovery

For simpler error propagation needs, consider anyhow. For derive-based error definitions, thiserror remains an excellent choice and can be used alongside Yoshi.

§Core Types

  • Yoshi: The main error type providing structured error handling
  • YoshiKind: Error categories with type-specific fields
  • YoContext: Contextual information and metadata
  • HatchExt: Extension trait for Result types
  • YoshiLocation: Source code location capture
  • YoshiBacktrace: Performance-monitored backtrace wrapper
  • NoStdIo: I/O error type for no_std environments
  • Result: Type alias for Result with Yoshi as default error
  • error_instance_count(): Global counter for Yoshi error instances

§Examples

Basic error creation and context addition:

use yoshi_std::{Yoshi, YoshiKind};

fn load_config(path: &str) -> Result<String, Yoshi> {
    // Convert I/O errors to Yoshi errors with additional context
    simulate_io_error()
        .map_err(Yoshi::from)?;

    // Errors can be built up with context as they propagate
    Err(Yoshi::new(YoshiKind::NotFound {
        resource_type: "config file".into(),
        identifier: path.into(),
        search_locations: None,
    })
    .with_metadata("config_path", path)
    .with_suggestion("Ensure the configuration file exists and is readable")
    .context(format!("Failed to load configuration from {}", path)))
}

match load_config("/etc/app/config.json") {
    Ok(config) => println!("Loaded: {}", config),
    Err(error) => {
        eprintln!("Configuration error: {}", error);
        // Rich error output includes context, metadata, and suggestions
    }
}

Working with typed payloads and structured data:

use yoshi_std::{Yoshi, YoshiKind};

#[derive(Debug)]
struct RequestId(String);

fn process_request(id: &str) -> Result<(), Yoshi> {
    Err(Yoshi::new(YoshiKind::Timeout {
        operation: "database query".into(),
        duration: std::time::Duration::from_secs(30),
        expected_max: Some(std::time::Duration::from_secs(10)),
    })
    .with_shell(RequestId(id.to_string()))
    .with_metadata("user_id", "12345")
    .context("Request processing failed"))
}

if let Err(error) = process_request("req_001") {
    // Access structured data from the error
    if let Some(request_id) = error.shell::<RequestId>() {
        println!("Failed request: {:?}", request_id);
    }

    println!("Error details: {}", error);
}
  • Structured error handling with context preservation [O(1) error creation, O(1) context attachment]
  • Type-safe error categorization with detailed diagnostic information [Memory-safe, Thread-safe]
  • Context chaining for complete error trace visibility [Stack-overflow protection, bounded depth]
  • Conditional backtrace capture with performance monitoring [Zero-cost when disabled]
  • Memory-efficient formatting with minimal allocations [Pre-allocated buffers, shared strings]

Modules§

async_error_handling
Advanced async error processing utilities with precise capturing and performance optimization.
cross_process_metrics
Global error metrics and telemetry system with cross-process coordination.
memory
Enhanced memory management utilities
process_communication
Cross-process error reporting and coordination with enterprise-grade reliability.
simd_optimization
SIMD-accelerated string processing for optimal error formatting performance.

Macros§

yoshi_location
Optimized macro for location capture with const evaluation.
yum
Debug macro that “eats” an error and prints it to stderr with full trace visibility.

Structs§

Arc
A thread-safe reference-counting pointer. ‘Arc’ stands for ‘Atomically Reference Counted’.
Box
A pointer type that uniquely owns a heap allocation of type T.
ContextAnalysis
Detailed context analysis results
OptimizedFormatBuffer
High-performance buffer for error formatting with safe optimizations
String
A UTF-8–encoded, growable string.
Vec
A contiguous growable array type, written as Vec<T>, short for ‘vector’.
YoContextserde
Enhanced structured context with performance optimizations and type safety.
Yoshi
The main Yoshi error type with enterprise-grade performance optimization.
YoshiBacktracestd
Performance-optimized backtrace wrapper with metadata.
YoshiLocationserde
Enhanced source code location with const evaluation.

Enums§

ErrorRecoveryStrategy
Comprehensive error recovery strategies
YoshiKind
High‑level categories for recoverable failures with performance optimizations.

Traits§

HatchExt
Extension trait for Result to easily attach Yoshi context, suggestions, and metadata.
Hatchable
Extension trait for mapping other Result<T, E> types into Hatch<T> easily.
LayContext
Trait that adds .lay(...) to Result<T, Yoshi>, enriching errors with context.
ToString
A trait for converting a value to a String.

Functions§

error_instance_count
Gets the current number of Yoshi error instances created.
intern_string
Optimized string interning function

Type Aliases§

Hatch
Ergonomic type alias for Result<T, Yoshi> with thematic naming.
Resultstd
Performance-optimized Result alias with mathematical precision guarantees.