How are you supposed to unwrap an error

68 points 9mHoq7ar4Z 70 comments

Hi All,

I feel like I am missing something obvious and so would like to understand what to do in this situation.

The Result traits unwrap functions seem to unwrap only Ok's and will panic when there is an Err. But I would like to unwrap the Err so that I can disclose it while running the program instead of panicking and crashing the program.

So for example consider the following where I am trying to unwrap the Err so that I can display the underlyng Error to std out.

use thiserror::Error;

#[derive(Error,Debug)]
enum Error {
    #[error ("This is a demo")]
    Demo
}

fn main() {
    let d: Result<(), Error> = Err(Error::Demo);
    println!("{d:?}");

    // println!("{}", d.unwrap()); // Results in panic

    println!("{}", // Now it unwraps d and displays 'This is a demo'
        if let Err(error) = d {
            format!("{error}")
        }
        else {
            format!("")
        }
    )

}

Using the if let to unwrap the Err seems very verbose and I feel like there must be a better method that I am unaware of.

Can anyone help?