Ergonomic and precise error handling provided by error sets. Inspired by Zig's error set type.

Overview

Error Set

github crates.io docs.rs build status

Error Set simplifies error management by providing a streamlined method for defining errors and easily converting between them. Resultingly, error handling becomes both straightforward and efficient.

Error Set is inspired by Zig's error set, and offers similar functionality.

Instead of defining various enums/structs for errors and hand rolling relations, use an error set:

use error_set::error_set;

error_set! {
    MediaError = BookParsingError || DownloadError || ParseUploadError;
    BookParsingError = {
        MissingBookDescription,
        IoError(std::io::Error),
    } || BookSectionParsingError;
    BookSectionParsingError = {
        MissingName,
        NoContents,
    };
    DownloadError = {
        InvalidUrl,
        IoError(std::io::Error),
    };
    ParseUploadError = {
        MaximumUploadSizeReached,
        TimedOut,
        AuthenticationFailed,
    };
}
Cargo Expand
#[derive(Debug)]
pub enum MediaError {
    MissingBookDescription,
    IoError(std::io::Error),
    MissingName,
    NoContents,
    InvalidUrl,
    MaximumUploadSizeReached,
    TimedOut,
    AuthenticationFailed,
}
#[allow(unused_qualifications)]
impl std::error::Error for MediaError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            MediaError::IoError(ref source) => source.source(),
            #[allow(unreachable_patterns)]
            _ => None,
        }
    }
}
impl core::fmt::Display for MediaError {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let variant_name = match *self {
            MediaError::MissingBookDescription => "MediaError::MissingBookDescription",
            MediaError::IoError(_) => "MediaError::IoError",
            MediaError::MissingName => "MediaError::MissingName",
            MediaError::NoContents => "MediaError::NoContents",
            MediaError::InvalidUrl => "MediaError::InvalidUrl",
            MediaError::MaximumUploadSizeReached => "MediaError::MaximumUploadSizeReached",
            MediaError::TimedOut => "MediaError::TimedOut",
            MediaError::AuthenticationFailed => "MediaError::AuthenticationFailed",
        };
        f.write_fmt($crate::format_args!("{}", variant_name))
    }
}
impl From<BookParsingError> for MediaError {
    fn from(error: BookParsingError) -> Self {
        match error {
            BookParsingError::MissingBookDescription => MediaError::MissingBookDescription,
            BookParsingError::IoError(source) => MediaError::IoError(source),
            BookParsingError::MissingName => MediaError::MissingName,
            BookParsingError::NoContents => MediaError::NoContents,
        }
    }
}
impl From<BookSectionParsingError> for MediaError {
    fn from(error: BookSectionParsingError) -> Self {
        match error {
            BookSectionParsingError::MissingName => MediaError::MissingName,
            BookSectionParsingError::NoContents => MediaError::NoContents,
        }
    }
}
impl From<DownloadError> for MediaError {
    fn from(error: DownloadError) -> Self {
        match error {
            DownloadError::InvalidUrl => MediaError::InvalidUrl,
            DownloadError::IoError(source) => MediaError::IoError(source),
        }
    }
}
impl From<ParseUploadError> for MediaError {
    fn from(error: ParseUploadError) -> Self {
        match error {
            ParseUploadError::MaximumUploadSizeReached => MediaError::MaximumUploadSizeReached,
            ParseUploadError::TimedOut => MediaError::TimedOut,
            ParseUploadError::AuthenticationFailed => MediaError::AuthenticationFailed,
        }
    }
}
impl From<std::io::Error> for MediaError {
    fn from(error: std::io::Error) -> Self {
        MediaError::IoError(error)
    }
}
#[derive(Debug)]
pub enum BookParsingError {
    MissingBookDescription,
    IoError(std::io::Error),
    MissingName,
    NoContents,
}
#[allow(unused_qualifications)]
impl std::error::Error for BookParsingError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            BookParsingError::IoError(ref source) => source.source(),
            #[allow(unreachable_patterns)]
            _ => None,
        }
    }
}
impl core::fmt::Display for BookParsingError {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let variant_name = match *self {
            BookParsingError::MissingBookDescription => "BookParsingError::MissingBookDescription",
            BookParsingError::IoError(_) => "BookParsingError::IoError",
            BookParsingError::MissingName => "BookParsingError::MissingName",
            BookParsingError::NoContents => "BookParsingError::NoContents",
        };
        f.write_fmt($crate::format_args!("{}", variant_name))
    }
}
impl From<BookSectionParsingError> for BookParsingError {
    fn from(error: BookSectionParsingError) -> Self {
        match error {
            BookSectionParsingError::MissingName => BookParsingError::MissingName,
            BookSectionParsingError::NoContents => BookParsingError::NoContents,
        }
    }
}
impl From<std::io::Error> for BookParsingError {
    fn from(error: std::io::Error) -> Self {
        BookParsingError::IoError(error)
    }
}
#[derive(Debug)]
pub enum BookSectionParsingError {
    MissingName,
    NoContents,
}
#[allow(unused_qualifications)]
impl std::error::Error for BookSectionParsingError {}

impl core::fmt::Display for BookSectionParsingError {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let variant_name = match *self {
            BookSectionParsingError::MissingName => "BookSectionParsingError::MissingName",
            BookSectionParsingError::NoContents => "BookSectionParsingError::NoContents",
        };
        f.write_fmt($crate::format_args!("{}", variant_name))
    }
}
#[derive(Debug)]
pub enum DownloadError {
    InvalidUrl,
    IoError(std::io::Error),
}
#[allow(unused_qualifications)]
impl std::error::Error for DownloadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            DownloadError::IoError(ref source) => source.source(),
            #[allow(unreachable_patterns)]
            _ => None,
        }
    }
}
impl core::fmt::Display for DownloadError {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let variant_name = match *self {
            DownloadError::InvalidUrl => "DownloadError::InvalidUrl",
            DownloadError::IoError(_) => "DownloadError::IoError",
        };
        f.write_fmt($crate::format_args!("{}", variant_name))
    }
}
impl From<std::io::Error> for DownloadError {
    fn from(error: std::io::Error) -> Self {
        DownloadError::IoError(error)
    }
}
#[derive(Debug)]
pub enum ParseUploadError {
    MaximumUploadSizeReached,
    TimedOut,
    AuthenticationFailed,
}
#[allow(unused_qualifications)]
impl std::error::Error for ParseUploadError {}

impl core::fmt::Display for ParseUploadError {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let variant_name = match *self {
            ParseUploadError::MaximumUploadSizeReached => {
                "ParseUploadError::MaximumUploadSizeReached"
            }
            ParseUploadError::TimedOut => "ParseUploadError::TimedOut",
            ParseUploadError::AuthenticationFailed => "ParseUploadError::AuthenticationFailed",
        };
        f.write_fmt($crate::format_args!("{}", variant_name))
    }
}

which is also equivalent to writing the full expansion:

error_set! {
    MediaError = {
        IoError(std::io::Error),
        MissingBookDescription,
        MissingName,
        NoContents,
        InvalidUrl,
        MaximumUploadSizeReached,
        TimedOut,
        AuthenticationFailed,
    };
    BookParsingError = {
        MissingBookDescription,
        IoError(std::io::Error),
        MissingName,
        NoContents,
    };
    BookSectionParsingError = {
        MissingName,
        NoContents,
    };
    DownloadError = {
        InvalidUrl,
        IoError(std::io::Error),
    };
    ParseUploadError = {
        MaximumUploadSizeReached,
        TimedOut,
        AuthenticationFailed,
    };
}

Any above subset can be converted into a superset with .into() or ?. This makes correctly scoping and passing around errors a breeze. Error enums and error variants can also accept doc comments and attributes like #[derive(...)]. The typical project approach is to have one errors.rs file with a single error_set. This keeps all the errors in one place and allows your IDE to autocomplete crate::errors:: with of all errors.

Basic Example
use error_set::error_set;

error_set! {
    MediaError = {
        IoError(std::io::Error)
    } || BookParsingError || DownloadError || ParseUploadError;
    BookParsingError = {
        MissingBookDescription,
        CouldNotReadBook(std::io::Error),
    } || BookSectionParsingError;
    BookSectionParsingError = {
        MissingName,
        NoContents,
    };
    DownloadError = {
        InvalidUrl,
        CouldNotSaveBook(std::io::Error),
    };
    ParseUploadError = {
        MaximumUploadSizeReached,
        TimedOut,
        AuthenticationFailed,
    };
}

fn main() {
    let book_section_parsing_error: BookSectionParsingError = BookSectionParsingError::MissingName;
    let book_parsing_error: BookParsingError = book_section_parsing_error.into();
    assert!(matches!(book_parsing_error, BookParsingError::MissingName));
    let media_error: MediaError = book_parsing_error.into();
    assert!(matches!(media_error, MediaError::MissingName));

    let io_error = std::io::Error::new(std::io::ErrorKind::OutOfMemory, "oops out of memory");
    let result_download_error: Result<(), DownloadError> = Err(io_error).coerce(); // `.coerce()` == `.map_err(Into::into)`
    let result_media_error: Result<(), MediaError> = result_download_error.coerce(); // `.coerce()` == `.map_err(Into::into)`
    assert!(matches!(result_media_error, Err(MediaError::IoError(_))));
}

Feature Flags

coerce_macro: Each error set will generates a coerce! macro to help handle coercion between partially intersecting sets.

let val = coerce!(setx => {
                    Ok(val) => val,
                    Err(SetX::X) => {}, // handle disjointedness
                    { Err(SetX) => return Err(SetY) } // terminal coercion
                })?;
More Details

Given:

error_set! {
   SetX = {
       X
   } || Common;
   SetY = {
       Y
   } || Common;
   Common = {
       A,
       B,
       C,
       D,
       E,
       F,
       G,
       H,
   };
}

rather than writing:

fn setx_result_to_sety_result() -> Result<(), SetY> {
   let _ok = match setx_result() {
       Ok(ok) => ok,
       Err(SetX::X) => {} // handle disjointedness
       Err(SetX::A) => {
           return Err(SetY::A);
       }
       Err(SetX::B) => {
           return Err(SetY::B);
       }
       Err(SetX::C) => {
           return Err(SetY::C);
       }
       Err(SetX::D) => {
           return Err(SetY::D);
       }
       Err(SetX::E) => {
           return Err(SetY::E);
       }
       Err(SetX::F) => {
           return Err(SetY::F);
       }
       Err(SetX::G) => {
           return Err(SetY::G);
       }
       Err(SetX::H) => {
           return Err(SetY::H);
       }
   };
   Ok(())
}

one can write this, which compiles to the match statement above:

fn setx_result_to_sety_result() -> Result<(), SetY> {
   let _ok = coerce!(setx_result() => {
       Ok(ok) => ok,
       Err(SetX::X) => {}, // handle disjointedness
       { Err(SetX) => return Err(SetY) } // terminal coercion
   });
   Ok(())
}

The coerce! macro is a flat fast (no tt muncher 🦫) declarative macro created by the error_set! macro for the set. coerce! behaves like a regular match statement, except it allows a terminal coercion statement between sets. e.g.

{ Err(SetX) => return Err(SetY) }
{ Err(SetX) => Err(SetY) }
{ SetX => return SetY }
{ SetX => SetY }

With coerce!, one can concisely handle specific variants of errors as they bubble up the call stack and propagate the rest.

tracing: Enables support for the tracing crate. Adds methods to Result that are applied on Err. Similar to anyhow's .context(..).

let value = result.warn("This a warning that will be passed to tracing if `Err`")?;

log: Enables support for the log crate. Adds methods to Result that are applied on Err. Similar to anyhow's .context(..).

let value = result.warn("This a warning that will be passed to log if `Err`")?;

Why Choose error_set Over thiserror or anyhow

If your project doesn't require handling specific error types and you just need to propagate errors up the call stack, then anyhow is likely a good choice for you. It's straightforward and skips the need to define error types all together.

However, for libraries and general projects that require precise error handling and differentiation, error management can often become complex and unwieldy, especially if "mega enums" arise.

What is a Mega Enum?

A mega enum, or mega error enum, is an enumeration that consolidates various error types into one large enum, whereas the code would be more precise if split into multiple enums. These often arise due to refactors or developers opting for less intrusive programming approach. This method can lead to inefficiencies and confusion because it includes error variants that are not relevant in certain scopes.

Example Scenario:

Consider the following functions and their respective error types:

  • func1 can produce errors a and b, represented by enum1.
  • func2 can produce errors c and d, represented by enum2.
  • func3 calls both func1 and func2.

If func3 does not handle the errors from func1 and func2, it must return an error enum that encompasses variants a, b, c, and d. Without a tool like error_set, developers might skip defining enum1 and enum2 due to the complexity and instead create a mega enum with all possible error variants (a, b, c, d). This means that any caller of func1 or func2 would have to handle all these cases, even those that are not possible in that specific context.

How error_set Simplifies Error Management:

error_set allows you to define errors quickly and precisely. Correctly scoping errors is easy and no wrapping of various error enum types is necessary, just use .into() or ? (or coerce! macro). This approach ensures that each function only deals with relevant error variants, avoiding the clutter and inefficiency of mega enums. By using error_set, your project can maintain clear and precise error definitions, enhancing code readability and maintainability without the tedious process of manually defining and managing error relations.

You might also like...
This library provides a convenient derive macro for the standard library's std::error::Error trait.

derive(Error) This library provides a convenient derive macro for the standard library's std::error::Error trait. [dependencies] therror = "1.0" Compi

A crate that allows you to mostly-safely cast one type into another type.

A crate that allows you to mostly-safely cast one type into another type. This is mostly useful for generic functions, e.g. pub fn fooS(s: S) {

A lightweight and ergonomic rust crate to handle system-wide hotkeys on windows

Windows Hotkeys An opinionated, lightweight crate to handle system-wide hotkeys on windows The windows-hotkeys crate abstracts and handles all interac

A high-level, ergonomic crate for interacting with the UploadThing API

utapi-rs A high-level, ergonomic Rust crate for interacting with the Uploadthing API. Why? If you're using Rust and want to use Uploadthing for file u

A library that creates a terminal-like window with feature-packed drawing of text and easy input handling. MIRROR.

BearLibTerminal provides a pseudoterminal window with a grid of character cells and a simple yet powerful API for flexible textual output and uncompli

Schemars is a high-performance Python serialization library, leveraging Rust and PyO3 for efficient handling of complex objects

Schemars Introduction Schemars is a Python package, written in Rust and leveraging PyO3, designed for efficient and flexible serialization of Python c

Pure Rust multi-line text handling
Pure Rust multi-line text handling

COSMIC Text Pure Rust multi-line text handling. COSMIC Text provides advanced text shaping, layout, and rendering wrapped up into a simple abstraction

Building blocks for handling potentially unsafe statics.

Grounded Building blocks for handling potentially unsafe statics. This crate aims to provide useful and sound components that serve as building blocks

plonky2 recursion framework handling different circuits in unified way.

generic_recursion Version: 0.1.0 generic_recursion is a crate that allows to easily aggregate an unlimited amount of plonky2 proofs, generated with a

Comments
  • feature request: inferred error variants.

    feature request: inferred error variants.

    A cool thing about zig error-sets is that error variants can be defined implicitly "on the fly" in the code. example:

    pub fn add_inferred(comptime T: type, a: T, b: T) !T {
        const ov = @addWithOverflow(a, b);
        if (ov[1] != 0) return error.Overflow;
        return ov[0];
    }
    

    here "OverFlow" has never been defined elsewhere. It just came to exist when actually returning it in the fn.

    Are there any plans for error-set to do something like this? Perhaps the rust macro system is not flexible enough....?

    reference: https://ziglang.org/documentation/master/#Inferred-Error-Sets

    community feedback wanted discussion 
    opened by dan-da 5
  • Can I attach a formatted message to each error variant?

    Can I attach a formatted message to each error variant?

    I am think something like what thiserror provides. So each enum variant can have a descriptive message.

    I see the warn() method, but that just logs a warning. I want to attach the error string for caller's usage.

    For some apps it can make sense not to use any strings, but I am evaluating error_set for usage in a crate that already uses both thiserror and anyhow to generate errors with descriptive messages.

    If it is already possible, please provide example usage.

    edit: I guess it might be possible to define error enums with thiserror and then merge them together with error_set. That is composable, but even more work and requires boths deps. I'd rather have a single dep and macro that an do both.

    enhancement 
    opened by dan-da 3
Releases(v0.4.2)
  • v0.4.2(Jul 24, 2024)

    • Improved parsing - better error messages and spans. Writing error sets will feel even more like native Rust.

    Full Changelog: https://github.com/mcmah309/error_set/compare/v0.4.1...v0.4.2

    Source code(tar.gz)
    Source code(zip)
  • v0.4.1(Jul 20, 2024)

  • v0.4.0(Jul 20, 2024)

    • Breaking: Move coerce! macro to behind a feature flag
    • Add tracing crate support behind tracing feature flag
    • Add log crate support behind log feature flag

    Full Changelog: https://github.com/mcmah309/error_set/compare/v0.3.2...v0.4.0

    Source code(tar.gz)
    Source code(zip)
  • v0.3.2(Apr 16, 2024)

  • v0.3.1(Apr 15, 2024)

  • v0.3.0(Apr 7, 2024)

Owner
Henry
Henry
SP3 Precise GNSS Orbit and Clock parser :artificial_satellite:

SP3 SP3 Precise GNSS Orbit files parser. SP3 is specifid by IGS. The parser only supports Revisions C & D at the moment and rejects revisions A & B. G

gwbres 4 Aug 31, 2023
Application microframework with command-line option parsing, configuration, error handling, logging, and shell interactions

Abscissa is a microframework for building Rust applications (either CLI tools or network/web services), aiming to provide a large number of features w

iqlusion 524 Dec 26, 2022
Rust CLI utility library. Error handling, status reporting, and exit codes.

narrate This library provides CLI application error and status reporting utilities. The coloured output formatting aims to be similar to Cargo. Error

Christopher Morton 5 Nov 2, 2022
Sets of libraries and tools to write applications and libraries mixing OCaml and Rust

Sets of libraries and tools to write applications and libraries mixing OCaml and Rust. These libraries will help keeping your types and data structures synchronized, and enable seamless exchange between OCaml and Rust

Meta 36 Jan 28, 2023
Given a set of kmers (fasta format) and a set of sequences (fasta format), this tool will extract the sequences containing the kmers.

Kmer2sequences Description Given a set of kmers (fasta / fastq [.gz] format) and a set of sequences (fasta / fastq [.gz] format), this tool will extra

Pierre Peterlongo 22 Sep 16, 2023
Terminal UI that allows Alacritty users to quickly and easily shuffle through provided themes 🦄

Alac-pretty alac-pretty.mp4 If you're like me in that you constantly need to change the colors of your dev environment because visual stagnation reall

Benji Nguyen 17 Aug 29, 2022
`rusty_regex` takes an input string and produces a `regex` string representing what was provided.

rusty_regex This project provides a binary that takes an input string, and preps it for regex usage, effectively replacing known generics and producin

Chris Speakes 2 Dec 31, 2022
A command line application which sets your wall paper with new image generating pollens once they arrive.

pollenwall Table of Contents pollenwall About Installation Binary releases Build from source Usage Command Line Arguments Running as a service MacOS L

Pollinations.AI 2 Jan 7, 2022
Dash is a CLI tool that rapidly sets up new projects by running a series of pre-defined commands.

Dash Dash is a CLI tool that rapidly sets up new projects by running a series of pre-defined commands. Features Quick Initialization: Initialize the c

Kunal Bagaria 4 Nov 7, 2023
Bam Error Stats Tool (best): analysis of error types in aligned reads.

best Bam Error Stats Tool (best): analysis of error types in aligned reads. best is used to assess the quality of reads after aligning them to a refer

Google 54 Jan 3, 2023