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,
}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: u8Context 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
impl YoContext
Sourcepub fn new(msg: impl Into<String>) -> Self
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 aString.
§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());Sourcepub fn with_metadata(self, k: impl Into<String>, v: impl Into<String>) -> Self
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 toString.v- The value for the metadata, convertible toString.
§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"));Sourcepub fn with_suggestion(self, s: impl Into<String>) -> Self
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 toString.
§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."));Sourcepub fn with_shell(self, shell: impl Any + Send + Sync + 'static) -> Self
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 implementAny,Send,Sync, and have a'staticlifetime.
§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]);Sourcepub fn shell<T: 'static>(&self) -> Option<&T>
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);Sourcepub fn add_shell_in_place(&mut self, shell: impl Any + Send + Sync + 'static)
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 implementAny,Send,Sync, and have a'staticlifetime.
§Examples
let mut ctx = YoContext::new("test");
ctx.add_shell_in_place(42u32);
assert!(ctx.shell::<u32>().is_some());Sourcepub fn with_priority(self, priority: u8) -> Self
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, au8value 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);Sourcepub fn with_location(self, location: YoshiLocation) -> Self
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- TheYoshiLocationto 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);