Crates.io | easy-error |
lib.rs | easy-error |
version | 1.0.0 |
source | src |
created_at | 2019-06-20 21:30:32.539103 |
updated_at | 2021-05-04 20:03:49.437372 |
description | Simple error utilities |
homepage | |
repository | https://gitlab.com/neachdainn/easy-error |
max_upload_size | |
id | 142431 |
size | 19,078 |
This crate is a lightweight error handling library meant to play well with the standard Error
trait.
It is designed for quick prototyping or for Command-line applications where any error will simply bubble up to the user.
There are four major components of this crate:
main
function.The current version requires Rustc 1.46 or newer. In general, this crate will be compilable with the Rustc version available on the oldest supported Ubuntu LTS release. Any change that requires a newer version of Rustc than what is available on the oldest supported Ubuntu LTS will be considered a breaking change.
use std::{fs::File, io::Read};
use easy_error::{bail, ensure, Error, ResultExt, Terminator};
fn from_file() -> Result<i32, Error> {
let file_name = "example.txt";
let mut file = File::open(file_name).context("Could not open file")?;
let mut contents = String::new();
file.read_to_string(&mut contents).context("Unable to read file")?;
contents.trim().parse().context("Could not parse file")
}
fn validate(value: i32) -> Result<(), Error> {
ensure!(value > 0, "Value must be greater than zero (found {})", value);
if value % 2 == 1 {
bail!("Only even numbers can be used");
}
Ok(())
}
fn main() -> Result<(), Terminator> {
let value = from_file().context("Unable to get value from file")?;
validate(value).context("Value is not acceptable")?;
println!("Value = {}", value);
Ok(())
}