Macro snafu::prelude::whatever

source ·
macro_rules! whatever {
    ($fmt:literal$(, $($arg:expr),* $(,)?)?) => { ... };
    ($source:expr, $fmt:literal$(, $($arg:expr),* $(,)?)*) => { ... };
}
Expand description

Instantiate and return a stringly-typed error message.

This can be used with the provided Whatever type or with a custom error type that uses snafu(whatever).

Without an underlying error

Provide a format string and any optional arguments. The macro will unconditionally exit the calling function with an error.

Examples

use snafu::{Whatever, prelude::*};

type Result<T, E = Whatever> = std::result::Result<T, E>;

enum Status {
    Sleeping,
    Chilling,
    Working,
}

fn do_laundry(status: Status, items: u8) -> Result<()> {
    match status {
        Status::Sleeping => whatever!("Cannot launder {items} clothes when I am asleep"),
        Status::Chilling => {
            stand_up();
            go_downstairs();
        }
        Status::Working => {
            go_downstairs();
        }
    }
    Ok(())
}

With an underlying error

Provide a Result as the first argument, followed by a format string and any optional arguments. If the Result is an error, the formatted string will be appended to the error and the macro will exit the calling function with an error. If the Result is not an error, the macro will evaluate to the Ok value of the Result.

Examples

use snafu::prelude::*;

#[derive(Debug, Snafu)]
#[snafu(whatever, display("Error was: {message}"))]
struct Error {
    message: String,
    #[snafu(source(from(Box<dyn std::error::Error>, Some)))]
    source: Option<Box<dyn std::error::Error>>,
}
type Result<T, E = Error> = std::result::Result<T, E>;

fn calculate_brightness_factor() -> Result<u8> {
    let angle = calculate_angle_of_refraction();
    let angle = whatever!(angle, "There was no angle");
    Ok(angle * 2)
}

fn calculate_angle_of_refraction() -> Result<u8> {
    whatever!("The programmer forgot to implement this...");
}