Managing errors

If you have used multiple libraries in Rust, you will probably have noticed that managing errors is not straightforward. We have the awesome ? operator, but if a function has multiple errors, it's not so easy to use. We can create our own error types, have variants for each of them, and have an Into trait implementation for each of the errors we might encounter. This is a tedious approach, but until recently it was the only way.

Luckily, we have a crate that can help us with that. This crate provides us with a Fail trait, which already guarantees thread safety and already provides default conversion implementations from all standard library error types. It also gives us some macros that help us with some boilerplate code. Let's see an example of how this would work:

extern crate failure;

use std::fs::File;
use std::io::Read;

use failure::{Error, ResultExt};

fn main() {
match read_file() {
Err(e) => {
eprintln!("Error: {}", e);

for cause in e.causes().skip(1) {
eprintln!("Caused by: {}", cause);
}
},
Ok(content) => {
println!("{}…",
content.chars()
.take(15)
.collect::<String>());
}
}
}

fn read_file() -> Result<String, Error> {
let file_name = "Cargo.toml";
let mut file = File::open(file_name)
.context("error opening the file")?;

let mut content = String::new();
file.read_to_string(&mut content)
.context("error reading the file")?;

Ok(content)
}

In this simple example, we get the first characters of the Cargo.toml file. As you can see, we are returning std::io::Errors converted into failure::Errors with the ? operator. Then, we can iterate over the errors if they exist. If something goes wrong, this will be the output of the code. We have added some context for each of the potential errors, so that the output gets properly printed:

You can also create your error traits and derive the Fail trait, thanks to the failure_derive crate. I recommend checking the complete documentation and using it for all your new projects. It brings many advantages over doing it yourself and even using the predecessor error-chain crate.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.237.29