Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Different Ways for 'Error Propagation' in Rust

DZone 's Guide to

Different Ways for 'Error Propagation' in Rust

See three different ways for error propagation in Rust.

· Integration Zone ·
Free Resource

Error Propagation means the code that detects the problem must propagate error information back to the caller function so that it can handle the problem. In the real world, the practice of Error Propagation is necessary. One of the benefits is that your code will look cleaner by simply propagating error information back to the caller that can handle the error. Another benefit is that your function doesn't need extra code to propagate both the successful and unsuccessful cases back to the caller. I won't go into details of this concept.

In this article, I will explain how you can do this in Rust in different ways.

  1. Using match 
use std::fs::File;
use std::io::Error;

fn open_file() -> Result<(), Error> {
    let file: Result<File, Error> = File::open("hello.txt");
    match file {
        Ok(_) => Ok(()),
        Err(e) => Err(e),
    }
}

fn main() {
    match open_file() {
        Ok(_) => println!("File is opened successfully!"),
        Err(e) => panic!(
            "Not able to open file. Here is the reason {:?}",
            e.to_string()
        ),
    }
}

If you are Rust developer, you would have known Result type, which is used to handle recoverable errors. In the above example, we are trying to open the file. File::open returns Result<File, Error>. We handle this value using match. If the file opened successfully, open_file will return Ok otherwise, pass the error value back to the caller function. Now caller function has to decide what to do with this error value. It can either create a new file hello.txt or show an error message.

2) Using try! 

The above example can be written in a much shorter way. Let's try with try. try! is a macro that returns Errs automatically in case of error otherwise it returns Ok variant. To use this macro, you have to use the raw-identifier syntax: r#try.

fn open_file() -> Result<(), Error> {
    let file = r#try!(File::open("hello.txt"));
    Ok(())
}

try! unwraps a result and early returns the function, if an error occurred.

3) Using ?operator 

We can even shorten above code using ? operator. This operator was added to replace try! and it's more idiomatic to use ? instead of try!.

fn open_file() -> Result<(), Error> {
    let file = File::open("hello.txt")?;
    Ok(())
}

As you can see this eliminates a lot of boilerplate and makes implementation simpler. I hope you enjoy reading this article. Let me know your thoughts in the comments!

Topics:
integration ,error propogation ,rust ,tutorial ,try ,operator ,match

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}