Reshaping errors in Rust
map_err rewrites the error while leaving a successful value alone.
fn read_port(text: &str) -> Result<u16, String> {
text.trim()
.parse::<u16>()
.map_err(|e| format!("bad port {text:?}: {e}"))
}
fn main() {
match read_port(" 8080 ") {
Ok(port) => println!("listening on {port}"),
Err(msg) => println!("{msg}"),
}
println!("{:?}", read_port("http"));
println!("{}", read_port("nope").unwrap_or_default());
}
How it works
map_errismapfor the error side.- It is how you fit a library error into your own type.
unwrap_or_defaultends the chain without a panic.
Keywords and builtins used here
ErrOkResultStringfnmainmatchread_portstru16
The run, in numbers
- Lines
- 14
- Characters to type
- 340
- Tokens
- 117
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 70 seconds.
Step 3 of 4 in Result & the ? operator, step 6 of 15 in Error handling.