4 releases (1 stable)

1.0.0 Apr 6, 2020
1.0.0-alpha.2 Nov 21, 2019
1.0.0-alpha.1 Sep 23, 2019
0.1.0-alpha.0 Sep 20, 2019

#6 in #des

Download history 16853/week @ 2024-05-22 18447/week @ 2024-05-29 15365/week @ 2024-06-05 14670/week @ 2024-06-12 15509/week @ 2024-06-19 17270/week @ 2024-06-26 9877/week @ 2024-07-03 8237/week @ 2024-07-10 9045/week @ 2024-07-17 8069/week @ 2024-07-24 8405/week @ 2024-07-31 6972/week @ 2024-08-07 7703/week @ 2024-08-14 7824/week @ 2024-08-21 7781/week @ 2024-08-28 7603/week @ 2024-09-04

32,468 downloads per month
Used in fehler

MIT/Apache

10KB
217 lines

Der Fehler

Documentation

Der Fehler is a library to add support for "throwing functions" to Rust through procedural macros. Functions marked with the throws attribute return Result, but the "Ok" path is used by default and you don't need to wrap ok return values in Ok. To throw errors, use ? or the throws macro.

Der Fehler provides these items:

The #[throws] attribute

The throws attribute modifies a function or method to make it return a Result. It takes an optional typename as an argument to the attribute which will be the error type of this function; if no typename is supplied, it uses the default error type for this crate.

Within the function body, returns (including the implicit final return) are automatically "Ok-wrapped." To raise errors, use ? or the throws! macro.

For example, these two functions are equivalent:

#[throws(i32)]
fn foo(x: bool) -> i32 {
    if x {
        0
    } else {
        throw!(1);
    }
}

fn bar(x: bool) -> Result<i32, i32> {
    if x {
        Ok(0)
    } else {
        Err(1)
    }
}

In functions that return Option

The attribute can be used to make a function that returns an Option using the as Option syntax, demonstrated below:

// This function returns `Option<i32>`
#[throws(as Option)]
fn foo(x: bool) -> i32 {
    if x {
        return 0;
    } else {
        throw!();
    }
}

The throw! macro

throw! is a macro which is equivalent to the Err($e)? pattern. It takes an error type and "throws" it.

One important aspect of the throw! macro is that it allows you to return errors inside of functions marked with throws. You cannot just return errors from these functions, you need to use this macro.

TODO

  • Make throws work on closures and async blocks (attributes are not allowed on expressions on stable)
  • Make throws work on Try types other than Result and Option (TRy is not on stable).

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~1.5MB
~36K SLoC