Macro snafu::whatever [−][src]
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.
use snafu::prelude::*;
#[derive(Debug, Snafu)]
#[snafu(whatever, display("Error was: {message}"))]
struct Error {
message: String,
}
type Result<T, E = Error> = std::result::Result<T, E>;
fn get_bank_account_balance(account_id: &str) -> Result<u8> {
if moon_is_rising() {
whatever!(
"We are recalibrating the dynamos for account {}, sorry",
account_id,
);
}
Ok(100)
}
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 exist the calling function with an error. If the Result
is
not an error, the macro will evaluate to the Ok
value of the
Result
.
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...");
}