Better way to print err and exit with different Result?

Say I have several functions that will return Result.
They have String Err but different Ok type.
I want to get ok value or print err message string and exit if there is an Err.
My code go like this:

let v1 = func1().unwrap_or_else( |err| {
    eprintln!("[Error]: {}", err);
    process::exit(1);
};
let v2 = func2().unwrap_or_else( |err| {
    eprintln!("[Error]: {}", err);
    process::exit(1);
};
// more functions like this

My question is how to reuse the print-and-exit code?
Function and closure will not work because the value's type in Ok is different.

1 Like

The try operator (?) can handle different Ok types.

Example:

fn func1() -> Result<String, String> { todo!() }
fn func2() -> Result<Vec<()>, String> { todo!() }

pub fn enclosing() -> Result<(), String> {
    let _v1 = func1()?;
    let _v2 = func2()?;
    Ok(())
}

pub fn elsewhere() {
    if let Err(err) = enclosing() {
        eprintln!("[Error]: {}", err);
        std::process::exit(1);
    }
}
7 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.