Implement FromStr With A Custom Error

Parse a domain value through FromStr with a dedicated error enum that wraps ParseIntError and reports empty, non-numeric, and out-of-range inputs distinctly.

RustData Integrity

Code

rustsnippet
51 lines
use std::fmt;
use std::num::ParseIntError;
use std::str::FromStr;

struct Port(u16);

// 自定义错误:区分空串、非数字与越界三种失败
#[derive(Debug)]
enum ParsePortError {
    Empty,
    NotANumber(ParseIntError),
    OutOfRange(u32),
}

impl fmt::Display for ParsePortError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ParsePortError::Empty => write!(f, "port string is empty"),
            ParsePortError::NotANumber(e) => write!(f, "not a number: {e}"),
            ParsePortError::OutOfRange(v) => write!(f, "port {v} outside 1..=65535"),
        }
    }
}

impl std::error::Error for ParsePortError {}

// 实现(implement)FromStr:之后 "443".parse::<Port>() 直接可用
impl FromStr for Port {
    type Err = ParsePortError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.is_empty() {
            return Err(ParsePortError::Empty);
        }
        let n: u32 = s.parse().map_err(ParsePortError::NotANumber)?;
        if (1..=65535).contains(&n) {
            Ok(Port(n as u16))
        } else {
            Err(ParsePortError::OutOfRange(n))
        }
    }
}

fn main() {
    for input in ["443", "0", "70000", "abc", ""] {
        match input.parse::<Port>() {
            Ok(Port(p)) => println!("ok: port {p}"),
            Err(e) => println!("rejected {input:?}: {e}"),
        }
    }
}

Inside the snippet

All of the logic lives in the functions fmt, from_str and main.

Repetition is confined to for input in ["443", "0", "70000", "abc", ""] — the rest of the file is straight-line. Result is the error channel: the caller receives the failure as a value instead of an exception. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

What to watch for

  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Putting it to use

The primary signature is fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result

Running the file prints labeled results such as ok: port, rejected — each operation’s effect is visible in the output.

Core lines

return Err(ParsePortError::Empty);
let n: u32 = s.parse().map_err(ParsePortError::NotANumber)?;
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ParsePortError::Empty => write!(f, "port string is empty"),
ParsePortError::NotANumber(e) => write!(f, "not a number: {e}"),
ParsePortError::OutOfRange(v) => write!(f, "port {v} outside 1..=65535"),
}
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
As data, not exceptions: `Result` makes the caller handle both arms.
What does Implement FromStr With A Custom Error print when run?
Execute the whole file; each printed line is prefixed with a label like `ok: port`, `rejected`.