iron/macros.rs
1//! Helper macros. Note that these are relatively new and may change in a later version.
2//!
3//! The idea is to use `itry` for internal server operations which can't be recovered from, and
4//! `iexpect` for validating user input. Note that this kind of usage is completely non-normative.
5//! Feedback about actual usability and usage is appreciated.
6
7/// Like `try!()`, but wraps the error value in `IronError`. To be used in
8/// request handlers.
9///
10/// The second (optional) parameter is any [modifier](modifiers/index.html).
11/// The default modifier is `status::InternalServerError`.
12///
13///
14/// ```ignore
15/// let f = itry!(fs::File::create("foo.txt"), status::BadRequest);
16/// let f = itry!(fs::File::create("foo.txt"), (status::NotFound, "Not Found"));
17/// let f = itry!(fs::File::create("foo.txt")); // HTTP 500
18/// ```
19///
20#[macro_export]
21macro_rules! itry {
22 ($result:expr) => (itry!($result, $crate::status::InternalServerError));
23
24 ($result:expr, $modifier:expr) => (match $result {
25 ::std::result::Result::Ok(val) => val,
26 ::std::result::Result::Err(err) => return ::std::result::Result::Err(
27 $crate::IronError::new(err, $modifier))
28 })
29}
30
31/// Unwrap the given `Option` or return a `Ok(Response::new())` with the given
32/// modifier. The default modifier is `status::BadRequest`.
33#[macro_export]
34macro_rules! iexpect {
35 ($option:expr) => (iexpect!($option, $crate::status::BadRequest));
36 ($option:expr, $modifier:expr) => (match $option {
37 ::std::option::Option::Some(x) => x,
38 ::std::option::Option::None => return ::std::result::Result::Ok(
39 $crate::response::Response::with($modifier))
40 })
41}