Crate flat_error

Crate flat_error 

Source
Expand description

Simple Error wrapper to ensure Clone, Debug, and PartialEq.

In general it is recommended that error types implement not just Error and it’s required Display, but also Clone, Debug, and PartialEq although Eq is optional. Beyond these additional traits are added as normal such as Copy, PartialOrd, Ord, Hash, etc.

However, there are a number of error types in the standard library, and many more in commonly used traits that do not meet this requirement. This simple crate introduces a new trait, ExtendedError, which provides these additional requirements and a new concrete type, FlatError which provides a way to capture existing errors such that they meet these requirements.

§Example

The following demonstrates a new type that meets the requirements of ExtendedError.

use std::{
    error::Error,
    fmt::{Display, Formatter, Result as FmtResult},
};

#[derive(Clone, Debug, PartialEq)]
pub struct MyError;

impl Display for MyError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "MyError")
    }
}

impl Error for MyError {}

However, the following fails because the error in std::io does not implement either Clone or PartialEq.

use std::{
    error::Error,
    fmt::{Display, Formatter, Result as FmtResult},
    io::Error as IoError,
};

#[derive(Clone, Debug, PartialEq)]
pub enum MyError {
    Io(IoError), // <= this doesn't work.
}

FlatError allows the capture and flattening of these errors into MyError, as shown below. This does however lose the ability to access any specific methods on the flattened error such as last_os_error on std::io::Error.

use flat_error::FlatError;
use std::{
    error::Error,
    fmt::{Display, Formatter, Result as FmtResult},
    io::Error as IoError,
};

#[derive(Clone, Debug, PartialEq)]
pub enum MyError {
    Io(FlatError),
}

§Features

  • std; Uses the std library. This is only really relevant for implementing From for errors in the std crate.
  • alloc; Uses the alloc and core libraries.

Structs§

FlatError
A FlatError is used to capture an error that does not meet the requirements of the trait ExtendedError and flatten it into a form that does.

Traits§

ExtendedError
This trait captures a minimum set of behaviors for error types that includes Clone, Debug, and PartialEq.