Inspect Failures Without Consuming Results

Use Result::inspect_err to log a failure while forwarding the same Result, keeping the error type intact where map_err would rewrite it.

RustResilience

Code

rustsnippet
32 lines
fn parse_port(raw: &str) -> Result<u16, String> {
    raw.trim()
        .parse::<u16>()
        .map_err(|e| format!("port {raw:?} is not a number: {e}"))
}

fn main() {
    let candidates = ["8080", " 443 ", "eighty", "70000"];

    // inspect_err:失败时做一次副作用(这里是打印),结果原样往下传
    let parsed: Vec<Result<u16, String>> = candidates
        .iter()
        .copied()
        .map(|raw| parse_port(raw).inspect_err(|err| println!("rejected: {err}")))
        .collect();

    let ok_count = parsed.iter().filter(|r| r.is_ok()).count();
    println!("accepted {} of {}", ok_count, parsed.len());

    // 结果还在手里:可以继续取第一个成功值
    let first_ok = parsed.iter().find_map(|r| r.as_ref().ok().copied());
    println!("first accepted: {first_ok:?}");

    // 同一组输入还能再收集一次:遇到第一个 Err 就短路
    let all: Result<Vec<u16>, String> = candidates
        .iter()
        .copied()
        .map(parse_port)
        .collect();
    println!("all valid: {}", all.is_ok());
    println!("first failure: {:?}", all.as_ref().err());
}

What the code does

All of the logic lives in the functions parse_port and main.

Fallible operations return Result, forcing the caller to handle both arms explicitly.

Watch out for

  • Nothing to add to the project before running it.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

The primary signature is fn parse_port(raw: &str) -> Result<u16, String>

The run interleaves both sides of the stream: a rejected: line prints from inspect_err for each bad candidate (eighty and 70000 fail parsing), accepted 2 of 4 counts what survived, and first accepted: Some(8080) shows the Results were kept rather than consumed by the inspection.

main calls 1 helper in sequence: parse_port.

Key statements

let ok_count = parsed.iter().filter(|r| r.is_ok()).count();
let first_ok = parsed.iter().find_map(|r| r.as_ref().ok().copied());
fn parse_port(raw: &str) -> Result<u16, String> {
raw.trim()
.parse::<u16>()
.map_err(|e| format!("port {raw:?} is not a number: {e}"))
}

Interactive Tools for This Topic

FAQ

Is there exception handling?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
What does Inspect Failures Without Consuming Results print when run?
Run it as a complete program — the output lines carry labels such as `rejected:`, `accepted`, `first accepted:`.