ContextExt

Trait ContextExt 

Source
pub trait ContextExt<T, E> {
    // Required methods
    fn context<C>(self, context: C) -> Result<T>
       where C: Display + Send + Sync + 'static;
    fn with_context<C, F>(self, f: F) -> Result<T>
       where C: Display + Send + Sync + 'static,
             F: FnOnce() -> C;
}
Expand description

Extension trait for ergonomic error context attachment.

This trait provides methods to add context to errors, making it easier to understand where and why an error occurred. It works with both Result<T, E> and Option<T> types.

§When to Use

  • Use context() when you have a static context message
  • Use with_context() when the context message is expensive to compute (it’s only evaluated on error)

§Library vs Application Code

  • Library code: Use this trait for adding context within the library
  • Application code: Consider using anyhow::Context for richer error handling

§Examples

§Adding Context to Results

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

fn fetch_ticker(symbol: &str) -> Result<f64> {
    // Static context (always evaluated)
    let data = fetch_raw_data()
        .context("Failed to fetch raw data")?;
     
    // Lazy context (only evaluated on error)
    parse_price(&data)
        .with_context(|| format!("Failed to parse price for {}", symbol))
}

§Adding Context to Options

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

fn get_required_field(json: &serde_json::Value) -> Result<&str> {
    json.get("field")
        .and_then(|v| v.as_str())
        .context("Missing required field 'field'")
}

Required Methods§

Source

fn context<C>(self, context: C) -> Result<T>
where C: Display + Send + Sync + 'static,

Adds context to an error.

Source

fn with_context<C, F>(self, f: F) -> Result<T>
where C: Display + Send + Sync + 'static, F: FnOnce() -> C,

Adds lazy context to an error (only evaluated on error).

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> ContextExt<T, Error> for Option<T>

Source§

fn context<C>(self, context: C) -> Result<T>
where C: Display + Send + Sync + 'static,

Source§

fn with_context<C, F>(self, f: F) -> Result<T>
where C: Display + Send + Sync + 'static, F: FnOnce() -> C,

Source§

impl<T, E> ContextExt<T, E> for Result<T, E>
where E: Into<Error>,

Source§

fn context<C>(self, context: C) -> Result<T>
where C: Display + Send + Sync + 'static,

Source§

fn with_context<C, F>(self, f: F) -> Result<T>
where C: Display + Send + Sync + 'static, F: FnOnce() -> C,

Implementors§