abscissa_core/error/
macros.rs

1//! Error-handling macros for the `abscissa` framework
2//!
3//! This crate defines two error handling macros designed to produce formatted
4//! error messages from error kind enums that implement the `Fail` trait:
5//!
6//! * `err!(kind, description)` creates a new `Error<Kind>` with the given
7//!   description. If additional parameters are given, `description` is treated as
8//!   a format string, e.g. `err!(kind, "something went wrong: {}", &wrongness)`.
9//! * `fail!(kind, description)` creates a new `Error<kind>` and returns it.
10
11/// Create a new error (of a given kind) with a formatted message
12#[macro_export]
13macro_rules! format_err {
14    ($kind:expr, $msg:expr) => {
15        $kind.context($crate::error::Message::new($msg))
16    };
17    ($kind:expr, $fmt:expr, $($arg:tt)+) => {
18        format_err!($kind, &format!($fmt, $($arg)+))
19    };
20}
21
22/// Create and return an error with a formatted message
23#[macro_export]
24macro_rules! fail {
25    ($kind:expr, $msg:expr) => {
26        return Err(format_err!($kind, $msg).into())
27    };
28    ($kind:expr, $fmt:expr, $($arg:tt)+) => {
29        fail!($kind, &format!($fmt, $($arg)+))
30    };
31}
32
33/// Ensure a condition holds, returning an error if it doesn't (ala assert)
34#[macro_export]
35macro_rules! ensure {
36    ($cond:expr, $kind:expr, $msg:expr) => {
37        if !($cond) {
38            return Err(format_err!($kind, $msg).into());
39        }
40    };
41    ($cond:expr, $kind:expr, $fmt:expr, $($arg:tt)+) => {
42        ensure!($cond, $kind, format!($fmt, $($arg)+))
43    };
44}
45
46/// Terminate the application with a fatal error, running Abscissa's shutdown hooks.
47///
48/// This macro is useful in cases where you don't have a particular error type
49/// you'd like to use when exiting but would like to have a formatted error
50/// message. If you do have a suitable error type, use `fatal_error!()` instead.
51///
52/// Takes the same arguments as `format!()`.
53#[macro_export]
54macro_rules! fatal {
55    ($app:expr, $msg:expr) => {
56        $crate::application::exit::fatal_error($app, $crate::error::Message::new($msg))
57    };
58    ($app:expr, $fmt:expr, $($arg:tt)+) => {
59        fatal!($app, format!($fmt, $($arg:tt)+))
60    };
61}