dyn-error

Crates.iodyn-error
lib.rsdyn-error
version0.2.2
sourcesrc
created_at2024-04-18 14:12:05.582839
updated_at2024-09-19 14:10:15.575046
descriptionError-related utilites for Rust
homepage
repositoryhttps://github.com/giancosta86/dyn-error
max_upload_size
id1212585
size15,435
Gianluca Costa (giancosta86)

documentation

README

dyn-error

Error-related utilites for Rust

Crates.io Version

This crate provides error-related utilities.

In particular, the assert_err_box macro is a minimalist way to test the inner value of an Err<Box<dyn Error>> from a Result:

use dyn_error::*;
use std::error::Error;
use std::fmt::Display;

#[derive(Debug, PartialEq, Eq)]
struct MyErr(pub u8);

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

impl Error for MyErr {}

fn main() -> Result<(), Box<dyn Error>> {
    let result: Result<String, Box<dyn Error>> = Err(Box::new(MyErr(90)));

    assert_err_box!(result, MyErr(90));
    Ok(())
}

For more fine-grained control, the check_err_box function performs the same test but returns a Result in lieu of calling panic:

use dyn_error::*;
use std::error::Error;
use std::fmt::Display;

//
// Declaring a custom Error type
//
#[derive(Debug, PartialEq, Eq)]
struct MyErr(pub u8);

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

impl Error for MyErr {}

//
// Test scenarios
//
fn main() -> Result<(), Box<dyn Error>> {
    let result: Result<String, Box<dyn Error>> = Err(Box::new(MyErr(90)));
    assert_eq!(check_err_box(result, MyErr(90)), Ok(()));

    let result: Result<String, Box<dyn Error>> = Err(Box::new(MyErr(90)));
    assert_eq!(
        check_err_box(result, MyErr(7)),
        Err(ErrBoxCheckFailure::NotEqual {
            expected: "Custom error: 7".to_string(),
            actual: "Custom error: 90".to_string()
        })
    );

    Ok(())
}

Crates.io

https://crates.io/crates/dyn-error

Documentation

https://docs.rs/dyn-error

License

MIT

Commit count: 7

cargo fmt