DEV Community

Discussion on: Error Handling in Rust programming language

 
aminmansuri profile image
hidden_dude

So if you have the following function:

fn myFunc() {
   option opt1 = f1()
   option opt2 = f2()
   // do more
}

If f1() returns an error will that cause f2() not to execution and myFunc() to fail?

If the answer is no then I have no choice to write horrible code like:

fn myFunc() {
   option opt1 = f1()
   if (opt1.isError()) return ERROR;
   option opt2 = f2()
   if (opt2.isError()) return ERROR;
   // do more
}

Ie. we're back to prehistory of error checking where all I see is error checking code. Low signal to noise ratio.

Code like this looks super messy to me:

fn read_username_from_file() -> Result<String, io::Error> {
    let f = File::open("hello.txt");

    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };

    let mut s = String::new();

    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}

The error handling is all mixed into the business logic.