fatal!() { /* proc-macro */ }Expand description
A declarative macro for handling critical, unrecoverable errors.
The fatal! macro wraps a block of code, allowing for a clean and
expressive “fail-fast” pattern. It provides a highly visible boundary for
code that is expected to be infallible, and it signals a critical bug if a
Result::Err is returned.
This macro is a more ergonomic and readable alternative to
ⓘ
(|| -> Result<_, anyhow::Error> { ... })().unwrap()§Behavior
- Allows
?Operator: The macro wraps the provided block in a closure, enabling the use of the?operator for seamless error propagation. - Detailed Panic: If the block returns an
Err, the macro catches the error, prints a detailed error message which includes any context. For this reason it is recommended to use thecontextfunction fromanyhow. - Returns a Value: The macro returns the inner value of the
Okvariant, allowing it to be used in assignments.
§Usage
The macro accepts a code block that must return a Result type.
ⓘ
use thiserror::Error;
use impass::fatal;
// Declare an error type for demonstration purposes.
#[derive(Error, Debug)]
pub enum MyError {
#[error("This operation failed")]
OperationFailed
}
// A fallible function for demonstration.
fn might_fail(value: i32) -> Result<i32, MyError> {
if value < 10 {
Err(MyError::OperationFailed)
} else {
Ok(value * 2)
}
}
fn main() {
// Simple usage without a custom message.
let final_value = fatal! {
let value = might_fail(15)?;
Ok(value)
};
println!("Successfully computed: {}", final_value);
// Usage with a custom message using the `#![reason]` attribute.
fatal! {
#![reason("Failed to initialize system-critical component.")]
let result = might_fail(5)?; // This will cause a panic.
Ok(())
}
}