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.

RustConfig Management

Code

rustsnippet
39 lines
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 own match.

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

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.