A custom error enum in Rust
One enum per failure mode, with a Display impl that reads like a sentence.
use std::fmt;
#[derive(Debug)]
enum ConfigError {
Missing(String),
OutOfRange { field: String, value: i64 },
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConfigError::Missing(key) => write!(f, "missing key {key}"),
ConfigError::OutOfRange { field, value } => {
write!(f, "{field} out of range: {value}")
}
}
}
}
fn main() {
let err = ConfigError::OutOfRange {
field: "port".to_string(),
value: 99999,
};
println!("{err}");
println!("{:?}", ConfigError::Missing("host".to_string()));
}
How it works
- Each variant carries the detail that failure needs.
impl Displayis what makes it printable.- Matching on the enum lets callers react per variant.
Keywords and builtins used here
ConfigErrorResultStringenumfmtfnfori64implletmainmatchmutselfuse
The run, in numbers
- Lines
- 27
- Characters to type
- 548
- Tokens
- 153
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 87 seconds.
Step 1 of 5 in Your own error types, step 8 of 15 in Error handling.