Struct YoContext

Source
pub struct YoContext {
    pub message: Option<Arc<str>>,
    pub metadata: HashMap<Arc<str>, Arc<str>>,
    pub suggestion: Option<Arc<str>>,
    pub location: Option<YoshiLocation>,
    pub payloads: Vec<Arc<Box<dyn Any + Send + Sync + 'static>>>,
    pub created_at: Option<SystemTime>,
    pub priority: u8,
}
Available on crate feature serde only.
Expand description

Enhanced structured context with performance optimizations and type safety.

YoContext provides additional, application-specific information about an error that helps in debugging, logging, and recovery. It supports messages, metadata, suggestions, and arbitrary typed payloads.

Fields§

§message: Option<Arc<str>>

Main message with Arc optimization for shared contexts.

This field holds a descriptive message for the context.

§metadata: HashMap<Arc<str>, Arc<str>>

Metadata with optimized storage for common keys.

A hash map storing key-value pairs of additional diagnostic information. Keys and values are Arc<str> for efficient sharing.

§suggestion: Option<Arc<str>>

Recovery suggestion with shared storage.

An optional human-readable suggestion for how to resolve or work around the error.

§location: Option<YoshiLocation>

Source location with compile-time capture.

An optional YoshiLocation indicating where this context was added in the source code.

§payloads: Vec<Arc<Box<dyn Any + Send + Sync + 'static>>>

Typed payloads with optimized storage.

A vector of arbitrary Any + Send + Sync + 'static types, allowing for rich, structured data to be attached to an error. Shells are shared across cloned contexts via Arc to ensure memory efficiency.

§created_at: Option<SystemTime>

Context creation timestamp for debugging.

An optional SystemTime indicating when this context was created.

§priority: u8

Context priority for error handling (0-255, higher is more important).

A numerical value indicating the importance or relevance of this context relative to other contexts attached to the same error.

Implementations§

Source§

impl YoContext

Source

pub fn new(msg: impl Into<String>) -> Self

Creates a new context with optimized string allocation.

This is the primary way to create a new YoContext. It automatically captures the current system time and sets a default priority. Uses string interning for memory efficiency.

§Arguments
  • msg - The main message for this context. It can be any type that converts into a String.
§Returns

A new YoContext instance.

§Examples
let ctx = YoContext::new("Attempting to connect to database");
assert_eq!(ctx.message.as_deref(), Some("Attempting to connect to database"));
assert!(ctx.created_at.is_some());
Source

pub fn with_metadata(self, k: impl Into<String>, v: impl Into<String>) -> Self

Adds metadata with optimized string interning.

This method allows attaching arbitrary key-value metadata to the context. It consumes self and returns a modified Self, enabling method chaining.

§Arguments
  • k - The key for the metadata, convertible to String.
  • v - The value for the metadata, convertible to String.
§Returns

The YoContext instance with the new metadata added.

§Examples
let ctx = YoContext::new("Processing user request")
    .with_metadata("user_id", "12345")
    .with_metadata("session_id", "abcde");

assert_eq!(ctx.metadata.get("user_id".into()).map(|s| s.as_ref()), Some("12345"));
Source

pub fn with_suggestion(self, s: impl Into<String>) -> Self

Adds a suggestion with shared storage optimization.

This method attaches a human-readable suggestion to the context, guiding users or operators on how to resolve the error. It consumes self and returns a modified Self.

§Arguments
  • s - The suggestion message, convertible to String.
§Returns

The YoContext instance with the suggestion added.

§Examples
let ctx = YoContext::new("File not found")
    .with_suggestion("Ensure the file path is correct and accessible.");

assert_eq!(ctx.suggestion.as_deref(), Some("Ensure the file path is correct and accessible."));
Source

pub fn with_shell(self, shell: impl Any + Send + Sync + 'static) -> Self

Attaches a typed shell with enhanced type safety.

This method allows attaching typed payloads with better type tracking for safer retrieval and debugging. Each shell is tagged with its type name.

§Arguments
  • shell - The data to attach. It must implement Any, Send, Sync, and have a 'static lifetime.
§Returns

The YoContext instance with the shell added. /// # Examples

#[derive(Debug, PartialEq)]
struct ErrorDetails {
    code: u16,
    reason: String,
}

let ctx = YoContext::new("API call failed")
    .with_shell(ErrorDetails { code: 404, reason: "Endpoint not found".to_string() })
    .with_shell(vec![1, 2, 3]);

let details = ctx.payloads.iter().find_map(|p| p.downcast_ref::<ErrorDetails>());
assert!(details.is_some());
assert_eq!(details.unwrap().code, 404);    ///
let vector_payload = ctx.payloads.iter().find_map(|p| p.downcast_ref::<Vec<i32>>());
assert!(vector_payload.is_some());
assert_eq!(vector_payload.unwrap(), &vec![1, 2, 3]);
Source

pub fn shell<T: 'static>(&self) -> Option<&T>

Gets a typed shell from this context.

This method attempts to retrieve a shell of the specified type from this context. It searches through all payloads and returns the first one that matches the type.

§Type Parameters
  • T - The type of shell to retrieve.
§Returns

An Option containing a reference to the shell of type T, or None if no such shell exists.

§Examples
#[derive(Debug, PartialEq)]
struct CustomData(u32);
let ctx = YoContext::new("test").with_shell(CustomData(123));
assert_eq!(ctx.shell::<CustomData>().unwrap().0, 123);
Source

pub fn add_shell_in_place(&mut self, shell: impl Any + Send + Sync + 'static)

Adds a typed shell in-place without taking ownership of the context.

This method allows attaching typed payloads without consuming the context, making it suitable for use with mutable references.

§Arguments
  • shell - The data to attach. It must implement Any, Send, Sync, and have a 'static lifetime.
§Examples
let mut ctx = YoContext::new("test");
ctx.add_shell_in_place(42u32);
assert!(ctx.shell::<u32>().is_some());
Source

pub fn with_priority(self, priority: u8) -> Self

Sets the priority level for this context.

The priority helps in ordering and selecting the most relevant contexts when an error is formatted or processed. Higher values indicate higher priority.

§Arguments
  • priority - The priority level, a u8 value from 0 to 255.
§Returns

The YoContext instance with the updated priority.

§Examples
let low_priority_ctx = YoContext::new("Minor detail").with_priority(50);
assert_eq!(low_priority_ctx.priority, 50);

let high_priority_ctx = YoContext::new("Critical information").with_priority(250);
assert_eq!(high_priority_ctx.priority, 250);
Source

pub fn with_location(self, location: YoshiLocation) -> Self

Sets location information on this context.

This method attaches source code location information to the context, helping with debugging and error tracing. It consumes self and returns a modified Self.

§Arguments
  • location - The YoshiLocation to set.
§Returns

The YoContext instance with the location set.

§Examples
let location = YoshiLocation::new("src/main.rs", 10, 5);
let ctx = YoContext::new("operation failed")
    .with_location(location);

assert_eq!(ctx.location.unwrap().file, "src/main.rs");
assert_eq!(ctx.location.unwrap().line, 10);

Trait Implementations§

Source§

impl Clone for YoContext

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for YoContext

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for YoContext

Source§

fn default() -> YoContext

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for YoContext

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for YoContext

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,