Jump to content

Rust - How to use map err to Handle Result

From JOHNWICK

We can call the map_err method on any Result value. If the Result is Err, map_err applies the function to transform the error. If the Result is Ok, it does nothing. In other words, we use map_err to manipulate the value inside an Err.

https://youtu.be/3ZiRLOd6gjY?si=RdGFxxFyNE08ZPBQ

fn main() {
    let b = hello(11).map_err(|e|{
        println!("error : {}", e);
        format!("The error is {}", e)
    } );

    println!("b: {:?}", b);
}

fn hello(a : i32) -> Result<String, String> {
    if a < 10 {
        Ok("hello".to_string())
    } else {
        Err("world".to_string())
    }
}

We define a hello function that returns a Result based on the value of the parameter a. In the main function, we call hello.

  • If we pass 1 as the argument, hello returns an Ok. In this case, map_err is not executed, and the result Ok("hello") is stored in the variable b.
  • If we pass 11 as the argument, hello returns an Err. This time, map_err is called. We pass a closure to map_err, which receives the value inside the Err. Inside the closure, we can manipulate that value—in this example, we simply print it and return a new formatted message. The closure’s return value then becomes the new Err, which is stored in the variable b.

Read the full article here: https://medium.com/@mikecode/rust-how-to-use-map-err-to-handle-result-925b3efb6e3e