#error #try #ergonomic

macro try-catch

A simple proc-macro that enables try-catch for Rust with automatic downcasting of error types

4 releases

0.2.2 Aug 21, 2021
0.2.1 Aug 21, 2021
0.2.0 Aug 21, 2021
0.1.0 Aug 21, 2021

#5 in #ergonomic

Download history 286/week @ 2023-12-03 235/week @ 2023-12-10 428/week @ 2023-12-17 380/week @ 2023-12-24 207/week @ 2023-12-31 398/week @ 2024-01-07 521/week @ 2024-01-14 237/week @ 2024-01-21 156/week @ 2024-01-28 346/week @ 2024-02-04 255/week @ 2024-02-11 268/week @ 2024-02-18 265/week @ 2024-02-25 224/week @ 2024-03-03 292/week @ 2024-03-10 265/week @ 2024-03-17

1,051 downloads per month
Used in 201 crates (3 directly)

Apache-2.0

9KB
140 lines

This crate provides a macro that enables the familiar try-catch syntax of other programming languages. It can be used to easlily group errors and manage them dynamically by type rather than value.

use try_catch::catch;
use std::*;
use serde_json::Value;

catch! {
    try {
        let number: i32 = "10".parse()?;
        let data = fs::read_to_string("data.json")?;
        let json: Value = serde_json::from_str(&data)?;
    }
    catch error: io::Error {
        println!("Failed to open the file: {}", error)
    }
    catch json_err: serde_json::Error {
        println!("Failed to serialize data: {}", json_err)
    }
    catch err {
        println!("Error of unknown type: {}", err)
    }
};

Note, if no wildcard is present then the compiler will warn about unused results. It can alo be used as an expression:

// We can guarantee that all errors are catched
// so the type of this expression is `i32`.
// It can be guarantieed because the final catch
// does not specify an Error type.
let number: i32 = catch! {
    try {
        let number: i32 = "10".parse()?;
        number
    } catch error {
        0
    }
};
// we can't know for sure if all possible errors are
// handled so the type is still Result.
let result: Result<i32, _> = catch! {
    try {
        let number: i32 = "10".parse()?;
        number
    } catch error: io::Error {
        0
    }
};

Dependencies

~1.5MB
~33K SLoC