Inspect Err Logs While Propagating
Log failures at the propagation boundary with Result::inspect_err, which runs a side effect and hands the untouched error back to the ? operator.
Code
use std::num::ParseIntError;
fn parse_port(raw: &str) -> Result<u16, ParseIntError> {
raw.parse::<u16>().inspect_err(|e| {
// 传播前记录一次现场:错误值原样继续向上走
eprintln!("parse failed for {raw:?}: {e}");
})
}
fn main() {
for input in ["8080", "70000", "not-a-port"] {
match parse_port(input) {
Ok(port) => println!("{input} -> {port}"),
Err(e) => println!("{input} -> rejected ({e})"),
}
}
}How it works
Inspect Err Logs While Propagating comes down to the functions parse_port and main.
Repetition is confined to for input in ["8080", "70000", "not-a-port"] — the rest of the file is straight-line. Fallible operations return Result, forcing the caller to handle both arms explicitly. match here is the control flow: arms enumerate the value’s shapes exhaustively.
What to watch for
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Applying it
Entry signature: fn parse_port(raw: &str) -> Result<u16, ParseIntError>
The demo flow inside main is parse_port — run the file to see it end to end.
Statements that matter
fn parse_port(raw: &str) -> Result<u16, ParseIntError> {
raw.parse::<u16>().inspect_err(|e| {
// 传播前记录一次现场:错误值原样继续向上走
eprintln!("parse failed for {raw:?}: {e}");
})
}
match parse_port(input) {
Ok(port) => println!("{input} -> {port}"),
Err(e) => println!("{input} -> rejected ({e})"),
}
Interactive Tools for This Topic
FAQ
- What happens when a call fails?
- Each fallible operation returns `Result`; nothing is silently discarded.
- How do you run Inspect Err Logs While Propagating?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.