Manual Display And Error Impls
Implement Display and std::error::Error by hand for a config error enum, keeping dependencies off the table while messages stay precise.
Code
use std::error::Error;
use std::fmt;
#[derive(Debug)]
enum ConfigError {
Missing(&'static str),
InvalidPort(String),
}
// 手写 Display:每种变体的报错文案精确可控
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Missing(key) => write!(f, "config key {key} is missing"),
ConfigError::InvalidPort(value) => write!(f, "invalid port {value:?}"),
}
}
}
// 实现 Error trait 才能接入 ? 与生态(source 默认返回 None)
impl Error for ConfigError {}
fn parse_port(raw: &str) -> Result<u16, ConfigError> {
let value: i64 = raw
.parse()
.map_err(|_| ConfigError::InvalidPort(raw.to_string()))?;
if (1..=65535).contains(&value) {
Ok(value as u16)
} else {
Err(ConfigError::InvalidPort(value.to_string()))
}
}
fn main() {
println!("{}", parse_port("8080").unwrap());
println!("{}", parse_port("70000").unwrap_err());
println!("{}", parse_port("eight").unwrap_err());
println!("{}", ConfigError::Missing("db_url"));
}How it works
Manual Display And Error Impls comes down to the functions fmt, parse_port and main.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
Signature: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
Running the file executes main, which drives parse_port in order.
Key statements
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigError::Missing(key) => write!(f, "config key {key} is missing"),
ConfigError::InvalidPort(value) => write!(f, "invalid port {value:?}"),
}
}
.map_err(|_| ConfigError::InvalidPort(raw.to_string()))?;
impl Error for ConfigError {}
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- How are errors reported?
- Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
- How do you run Manual Display And Error Impls?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.