rust / expert
Snippet
Constructing Custom Error Types with Dynamic Causality Chaining
Implementing std::error::Error with the source method allows custom errors to chain underlying failures. This facilitates debugging by preserving root-cause information, enabling callers to query the causality chain dynamically via downcasting or library helpers.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
use std::error::Error;use std::fmt;#[derive(Debug)]pub struct SubsystemError {pub detail: &'static str,}impl fmt::Display for SubsystemError {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {write!(f, "Subsystem failure: {}", self.detail)}}impl Error for SubsystemError {}#[derive(Debug)]pub struct ApplicationError {pub message: String,pub source: SubsystemError,}impl fmt::Display for ApplicationError {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {write!(f, "Application error occurred: {}", self.message)}}impl Error for ApplicationError {fn source(&self) -> Option<&(dyn Error + 'static)> {Some(&self.source)}}
Breakdown
1
impl Error for SubsystemError {}
Uses the default implementation of the Error trait, requiring the type to already implement Debug and Display.
2
pub source: SubsystemError,
Defines a field on the wrapper error that holds the original cause of the failure.
3
fn source(&self) -> Option<&(dyn Error + 'static)> {
Overrides the default source method to return a reference to the nested error trait object, enabling dynamic query traversal.