Crate exn

Crate exn 

Source
Expand description

A context-aware concrete Error type built on std::error::Error

§Examples

use exn::Result;
use exn::ResultExt;
use exn::bail;

// It's recommended to define errors as structs. Exn will maintain the error tree automatically.
#[derive(Debug)]
struct LogicError(String);

impl std::fmt::Display for LogicError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "logic error: {}", self.0)
    }
}

impl std::error::Error for LogicError {}

fn do_logic() -> Result<(), LogicError> {
    bail!(LogicError("0 == 1".to_string()));
}

// Errors can be enum but notably don't need to chain source error.
#[derive(Debug)]
enum AppError {
    Fatal { consequences: &'static str },
    Trivial,
}

impl std::fmt::Display for AppError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AppError::Fatal { consequences } => write!(f, "fatal error: {consequences}"),
            AppError::Trivial => write!(f, "trivial error"),
        }
    }
}

impl std::error::Error for AppError {}

fn main() {
    if let Err(err) = do_logic().or_raise(|| AppError::Fatal {
        consequences: "math no longer works",
    }) {
        eprintln!("{err:?}");
    }
}

The above program will print an error message like:

fatal error: math no longer works, at exn/src/lib.rs:44:16
|
|-> logic error: 0 == 1, at exn/src/lib.rs:40:5

Macros§

bail
Creates an Exn and returns it as Result.
ensure
Ensures $cond is met; otherwise return an error.

Structs§

Exn
An exception type that can hold an error tree and additional context.
Frame
A frame in the exception tree.

Traits§

Error
A trait bound of the supported error type of Exn.
OptionExt
An extension trait for Option to provide raising new exceptions on None.
ResultExt
An extension trait for Result to provide context information on Exns.

Functions§

Ok
Equivalent to Ok::<_, Exn<E>>(value).

Type Aliases§

Result
A reasonable return type to use throughout an application.