Skip to main content

WithContext

Trait WithContext 

Source
pub trait WithContext: StdError + Any {
    // Required methods
    fn with_context(self, context: Frame) -> Self;
    fn location(&self) -> Option<&'static Location<'static>>;
}
Expand description

A trait for error types that can carry context information.

Types implementing this trait can have context (message + location) attached to them via with_context. This is the core abstraction enabling the library’s context propagation.

§Implementing

For most use cases, use the impl_context_error! macro instead of implementing this manually.

§Example

use std::borrow::Cow;
use std::error::Error;
use std::fmt::{Debug, Display};
use std::panic::Location;

use scoped_error::Frame;
use scoped_error::WithContext;

// Custom error type with context support
#[derive(Debug)]
struct MyError {
    message: Cow<'static, str>,
    source: Option<Box<dyn Error + Send + Sync>>,
    location: Option<&'static Location<'static>>,
}

impl Error for MyError {}
impl Display for MyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(loc) = self.location {
            write!(f, "{}, at {}", self.message, loc)
        } else {
            f.write_str(&self.message)
        }
    }
}

impl WithContext for MyError {
    fn with_context(mut self, context: Frame) -> Self {
        self.source = Some(context.source);
        self.location = Some(context.location);
        self
    }

    fn location(&self) -> Option<&'static Location<'static>> {
        self.location
    }
}

Required Methods§

Source

fn with_context(self, context: Frame) -> Self

Attach a context layer to this error.

The context includes a source error and the location where the context was added (captured via #[track_caller]).

Source

fn location(&self) -> Option<&'static Location<'static>>

Get the location where this error was created or where context was attached.

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.

Implementors§