0 day streak
rust / expert
Snippet

Manual Error Source Chaining and Formatting

In plain Rust std without helper crates, idiomatic error handling requires implementing std::fmt::Display for user messages and std::error::Error::source to expose cause chains.

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
use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub enum PipelineError {
ParseFailed(String),
NetworkTimeout { target: String, cause: std::io::Error },
}
impl fmt::Display for PipelineError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ParseFailed(msg) => write!(f, "Data parsing failure: {}", msg),
Self::NetworkTimeout { target, .. } => write!(f, "Network request timed out for host: {}", target),
}
}
}
impl Error for PipelineError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::ParseFailed(_) => None,
Self::NetworkTimeout { cause, .. } => Some(cause),
}
}
}
Breakdown
1
pub enum PipelineError {
Declares a custom domain error enum capable of storing string context and nested IO errors.
2
impl fmt::Display for PipelineError {
Formats user-friendly error output for console or log reporting.
3
impl Error for PipelineError {
Implements the std Error trait to enable error source chaining.
4
Self::NetworkTimeout { cause, .. } => Some(cause),
Returns a dynamic trait object reference to the underlying causality error.