[][src]Crate evitable

Evitable

Evitable is a library for easily creating and using custom error types in libraries. It's intended to make the creation of custom domain specific error types easier, as well as reduce the noise related to converting from underlying errors to domain specific errors, while keeping the underlying error as source(). This crate by default has a feature called derive enabled, which enables deriving ErrorContexts.

Quick example

This example showcases a typical usecase of calling some API that (pretends) to read a file, only to fail, and then converts the error into a domain specific error.

use evitable::*;

// Typically, this is in another file
mod error {
  use super::*;

  #[derive(ErrorContext)]
  pub enum Context {
    #[evitable(description = "Io error", from = std::io::Error)]
    Io,

    #[evitable(description("Invalid token. Expected {}, was {}.", expected, actual))]
    InvalidToken {
       expected: String,
       actual: String,
    },
  }
}

use error::*;

// pretend token type
#[derive(Debug)]
pub enum Token {
  EndOfFile,
}

fn read_file() -> std::result::Result<String, std::io::Error> {
  // we're pretending to read a file here
  Err(std::io::Error::from(std::io::ErrorKind::NotFound))
}

// main function
fn parse_file() -> Result<Token> {
  let content = read_file()?;
  ensure!(content == "EOF", Context::InvalidToken {
    expected: "EOF".to_owned(),
    actual: content,
  });

  Ok(Token::EndOfFile)
}

let result = parse_file();
let err = result.unwrap_err();
assert_eq!(err.kind(), evitable_context::ErrorKind::Io);

Re-exports

pub use evitable_derive::ErrorContext;

Macros

ensure

Utility macro to return errors if a given condition is false.

fail

Utility macro to return errors.

Structs

Backtrace

Representation of an owned and self-contained backtrace.

Traits

ErrorContext

Error context trait, typically used with #[derive(ErrorContext)]. This produces Error and ErrorKind types for the given context.

EvitableError

Trait implemented for all error types generated by #[derive(ErrorContext)]. Allows for creating new errors from the ErrorContext, and allows getting the error kind.

EvitableErrorKind

Trait for "error kinds". An ErrorKind enum is generated for every #[derive(ErrorContext)] which typically just contains variants for each error variant (or just a single variant in case of error structs).

OptionExt

Extension trait for option and result types for easy convertion to evitable errors.

ResultExt

Extension trait for result types (and other types carrying errors with them).