macro_rules! ensure { ($cond:expr $(,)?) => { ... }; ($cond:expr, $msg:literal $(,)?) => { ... }; ($cond:expr, $fmt:expr, $($arg:tt)*) => { ... }; ($cond:expr, $error_code:expr) => { ... }; }
Expand description
Util macro for generating error when condition check failed.
§Case 1: Expression only.
ⓘ
ensure!(a < 0);
This will generate following error:
ⓘ
anyhow!("a < 0").into()
§Case 2: Error message only.
ⓘ
ensure!(a < 0, "a should not be negative!");
This will generate following error:
ⓘ
anyhow!("a should not be negative!").into();
§Case 3: Error message with argument.
ⓘ
ensure!(a < 0, "a should not be negative, value: {}", 1);
This will generate following error:
ⓘ
anyhow!("a should not be negative, value: 1").into();
§Case 4: Error code.
ⓘ
ensure!(a < 0, ErrorCode::MemoryError { layout });
This will generate following error:
ⓘ
ErrorCode::MemoryError { layout }.into();