Better Error Handling in Rust

If you have written any Rust, you may have noted how the above code uses Result<T> instead of Result<T, E>. This is because we have used a crate called anyhow.rs. Consider this function:

pub fn write_blob(self) {
    let blob_path = self.get_path();
    create_dir_all(blob_path.parent().unwrap()).unwrap();
    let mut file = File::create(blob_path).unwrap();
    file.write_all(&self.content).unwrap();
    file.flush().unwrap();
}

There are a number of ways this can fail. However, we don’t care a lot about the exact type of each error. We only want to know where the error occurred and why. The anyhow crate works best in such a scenario. Here’s the implementation of the sam e function with anyhow::Result. ¬†

pub fn write_blob(self) -> anyhow::Result<()> {
    let blob_path = self.get_path();
    create_dir_all(blob_path.parent()?)?;
    let mut file = File::create(blob_path)?;
    file.write_all(&self.content)?;
    file.flush()?;
}

As you can see, we are able to use the handy little ? operator even though each function call returns a different type of error.