capypad
0 day streak
rust / intermediate
Snippet

Custom Error Types Implementing std::error::Error

Implementing the Error trait for custom error types creates idiomatic error handling in Rust. The Error trait requires Display implementation and provides std::error::Error compatibility for propagation with the ? operator. This pattern enables structured error handling with domain-specific error variants.

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
34
35
36
37
38
39
40
use std::fmt;
use std::error::Error;
 
#[derive(Debug)]
enum ValidationError {
EmptyField(String),
InvalidFormat { field: String, expected: String },
}
 
impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ValidationError::EmptyField(field) => write!(f, "Field '{}' cannot be empty", field),
ValidationError::InvalidFormat { field, expected } => {
write!(f, "Field '{}' has invalid format. Expected: {}", field, expected)
}
}
}
}
 
impl Error for ValidationError {}
 
fn validate_input(value: &str, field_name: &str) -> Result<(), ValidationError> {
if value.is_empty() {
return Err(ValidationError::EmptyField(field_name.to_string()));
}
if !value.contains('@') && field_name == "email" {
return Err(ValidationError::InvalidFormat {
field: field_name.to_string(),
expected: "valid email address".to_string(),
});
}
Ok(())
}
 
fn main() {
if let Err(e) = validate_input("", "username") {
eprintln!("Validation failed: {}", e);
}
}
Breakdown
1
use std::fmt
Import fmt module for Display trait implementation
2
#[derive(Debug)]
Derive Debug for error formatting in debug output
3
enum ValidationError { EmptyField(String), InvalidFormat {...} }
Define enum with variants for different error scenarios
4
impl fmt::Display for ValidationError
Implement Display trait to format error messages as user-facing strings
5
impl Error for ValidationError {}
Implement std::error::Error trait enabling ? operator and error propagation
6
if let Err(e) = validate_input("", "username")
Pattern match on error result to handle validation failure