rust / expert
Snippet
Dynamic Error Downcasting and Context Contextualization
This snippet demonstrates how to define a custom error type and perform dynamic downcasting on a trait object of dyn Error. Using downcast_ref, the code inspects concrete error types at runtime, enabling specialized error recovery or context aggregation for specific failure modes.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use std::error::Error;use std::fmt;#[derive(Debug)]pub struct QueryError {pub query: String,}impl fmt::Display for QueryError {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {write!(f, "Query failed: {}", self.query)}}impl Error for QueryError {}pub fn process_error(err: &dyn Error) -> Option<&QueryError> {err.downcast_ref::<QueryError>()}
Breakdown
1
pub struct QueryError
Defines a custom error struct containing domain-specific context metadata.
2
impl fmt::Display for QueryError
Implements formatting to print a human-readable description of the error.
3
impl Error for QueryError {}
Marks the struct as a standard library Error, enabling its use as a trait object.
4
err.downcast_ref::<QueryError>()
Uses the downcast_ref method to check if the dynamic error matches QueryError.