dyn_error/
lib.rs

1//! This crate provides error-related utilities.
2//!
3//! In particular, the [assert_err_box] macro is a minimalist way
4//! to test the inner value of an `Err<Box<dyn Error>>` from a [Result]:
5//!
6//! ```
7//! use dyn_error::*;
8//! use std::fmt::Display;
9//! use std::error::Error;
10//!
11//! #[derive(Debug, PartialEq, Eq)]
12//! struct MyErr(pub u8);
13//!
14//! impl Display for MyErr {
15//!     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16//!         write!(f, "Custom error: {}", self.0)
17//!     }
18//! }
19//!
20//! impl Error for MyErr {}
21//!
22//! let result: Result<String, Box<dyn Error>> = Err(Box::new(MyErr(90)));
23//!
24//! assert_err_box!(result, MyErr(90));
25//! ```
26//!
27//! For more fine-grained control, the [check_err_box] function
28//! performs the same test but returns a [Result] in lieu of calling [panic]:
29//!
30//! ```
31//! use dyn_error::*;
32//! use std::fmt::Display;
33//! use std::error::Error;
34//!
35//! //
36//! // Declaring a custom Error type
37//! //
38//! #[derive(Debug, PartialEq, Eq)]
39//! struct MyErr(pub u8);
40//!
41//! impl Display for MyErr {
42//!     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43//!         write!(f, "Custom error: {}", self.0)
44//!     }
45//! }
46//!
47//! impl Error for MyErr {}
48//!
49//! //
50//! // Test scenarios
51//! //
52//! let result: Result<String, Box<dyn Error>> = Err(Box::new(MyErr(90)));
53//! assert_eq!(
54//!     check_err_box(result, MyErr(90)),
55//!     Ok(())
56//! );
57//!
58//! let result: Result<String, Box<dyn Error>> = Err(Box::new(MyErr(90)));
59//! assert_eq!(
60//!     check_err_box(result, MyErr(7)),
61//!     Err(ErrBoxCheckFailure::NotEqual {
62//!         expected: "Custom error: 7".to_string(),
63//!         actual: "Custom error: 90".to_string()
64//!     })
65//! );
66//! ```
67
68mod err_box;
69
70pub use err_box::*;