Skip to main content

handle

Macro handle 

Source
macro_rules! handle {
    (require $($rest:tt)+) => { ... };
    (scope $($rest:tt)+) => { ... };
    (try when $($rest:tt)+) => { ... };
    (async try { $($body:tt)* } , then $($rest:tt)+) => { ... };
    (async try { $($body:tt)* } $($rest:tt)+) => { ... };
    (async try { $($body:tt)* }) => { ... };
    (try { $($body:tt)* } , then $($rest:tt)+) => { ... };
    (try { $($body:tt)* } with $($with_and_rest:tt)+) => { ... };
    (try -> $type:ty { $($body:tt)* } , then $($rest:tt)+) => { ... };
    (try for $($all:tt)+) => { ... };
    (try any $($all:tt)+) => { ... };
    (try all $($all:tt)+) => { ... };
    (try while $($all:tt)+) => { ... };
    (try -> $type:ty { $($body:tt)* } $($rest:tt)+) => { ... };
    (try -> $type:ty { $($body:tt)* }) => { ... };
    (try { $($body:tt)* } $($rest:tt)+) => { ... };
    (try { $($body:tt)* }) => { ... };
    ($first:tt $($rest:tt)*) => { ... };
    () => { ... };
}
Expand description

Main error handling macro.

§Patterns

§Basic try

use handle_this::{handle, Result};

fn example() -> Result<i32> {
    handle! {
        try { Ok::<_, &str>(42)? }
        catch { -1 }
    }
}
assert_eq!(example().unwrap(), 42);

§Try for (first success)

use handle_this::{handle, Result};

fn example() -> Result<i32> {
    let items: Vec<std::result::Result<i32, &str>> = vec![Err("a"), Ok(42)];
    handle! {
        try for item in items { item? }
        catch { -1 }
    }
}
assert_eq!(example().unwrap(), 42);

§Try all (collect all successes)

use handle_this::{handle, Result};

fn example() -> Result<Vec<i32>> {
    let items = vec![1, 2, 3];
    handle! {
        try all item in items { Ok::<_, &str>(item * 2)? }
    }
}
assert_eq!(example().unwrap(), vec![2, 4, 6]);

§Try while (retry until success or condition false)

use handle_this::{handle, Result};

fn example() -> Result<&'static str> {
    let mut attempts = 0;
    handle! {
        try while attempts < 3 {
            attempts += 1;
            if attempts < 3 { Err("not yet")? }
            "success"
        }
        catch { "gave up" }
    }
}
assert_eq!(example().unwrap(), "success");