intermediateError Handling
Map and Transform Errors
Transform error types with map_err and and_then.
Map and Transform Errors
Transform error types with map_err and and_then.
Difficulty
Intermediate
Code
rust
use std::num::ParseIntError;
use std::fmt;
#[derive(Debug)]
struct AppError(String);
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "AppError: {}", self.0)
}
}
fn parse_age(input: &str) -> Result<u32, AppError> {
input.parse::<u32>()
.map_err(|e| AppError(format!("invalid age: {}", e)))
.and_then(|age| {
if age > 150 {
Err(AppError("age too high".into()))
} else {
Ok(age)
}
})
}
fn main() {
println!("{:?}", parse_age("25"));
println!("{:?}", parse_age("abc"));
println!("{:?}", parse_age("200"));
}Explanation
map_err and and_then transform errors.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the error-handling category to build a complete understanding of this topic.