[][src]Crate easy_error

Easy-error

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.32 or newer. In general, this crate will be compilable with the Rustc version available on the oldest Ubuntu LTS release. Any change that requires a new Rustc version will be considered a breaking change and will be handled accordingly.

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

Macros

bail

Exits a function early with an Error.

ensure

Exits a function early with an Error if the condition is not satisfied.

format_err

Creates an Error using the standard string interpolation syntax.

Structs

Causes

An iterator over the causes of an error.

Error

An error that is a human-targetted string plus an optional cause.

Terminator

An error that wraps all other error types for a nicer debug output.

Traits

ErrorExt

Extension methods to Error types.

ResultExt

Extension methods to the Result type.

Functions

err_msg

Creates an error message from the provided string.

Type Definitions

Result