3 stable releases

1.0.2 Jan 10, 2024
1.0.1 Jun 29, 2023

#201 in Rust patterns

Download history 415/week @ 2024-08-17 410/week @ 2024-08-24 529/week @ 2024-08-31 549/week @ 2024-09-07 393/week @ 2024-09-14 3499/week @ 2024-09-21 6184/week @ 2024-09-28 7507/week @ 2024-10-05 8657/week @ 2024-10-12 9461/week @ 2024-10-19 7620/week @ 2024-10-26 7757/week @ 2024-11-02 5129/week @ 2024-11-09 7447/week @ 2024-11-16 10890/week @ 2024-11-23 10403/week @ 2024-11-30

35,267 downloads per month
Used in 10 crates (9 directly)

MIT/Apache

13KB
103 lines

version-badge license-badge rust-version-badge

Adding 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.

A fork of Der Fehler updating dependencies and fixing issues while (by my understanding) boats is unable to contribute to open source.

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 {
        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.

Rust Version Policy

This crate only supports the current stable version of Rust, patch releases may use new features at any time.

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

~215–660KB
~16K SLoC