5 releases (1 stable)

1.0.0 May 4, 2021
0.3.1 Feb 15, 2020
0.3.0 Dec 21, 2019
0.2.0 Sep 18, 2019
0.1.0 Jun 20, 2019

#1014 in Rust patterns

Download history 3947/week @ 2023-11-24 1974/week @ 2023-12-01 1137/week @ 2023-12-08 1221/week @ 2023-12-15 276/week @ 2023-12-22 985/week @ 2023-12-29 1509/week @ 2024-01-05 843/week @ 2024-01-12 848/week @ 2024-01-19 324/week @ 2024-01-26 200/week @ 2024-02-02 420/week @ 2024-02-09 552/week @ 2024-02-16 496/week @ 2024-02-23 527/week @ 2024-03-01 308/week @ 2024-03-08

1,973 downloads per month
Used in 14 crates

MIT license

14KB
192 lines

Easy-error

docs.rs crates.io MIT License Rustc 1.46+ Pipeline

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:

  1. A basic, string-based error type that is meant for either quick prototyping or human-facing errors.
  2. A nice way to iterate over the causes of an error.
  3. Some macros that make returning errors slightly more ergonomic.
  4. A "termination" type that produces nicely formatted error messages when returned from the main function.

Rust Version Requirements

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.

Example

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(())
}

No runtime deps