Skip to main content

msg_bail_anyhow

Macro msg_bail_anyhow 

Source
macro_rules! msg_bail_anyhow {
    ($msg:expr) => { ... };
}
Expand description

Early return with an error created from a message.

This macro combines error creation with immediate return, providing a convenient way to exit functions early when error conditions are detected. It’s equivalent to return Err(msg_error_anyhow!(message)) but more concise.

§Early Return Pattern

  • Error Creation: Creates an anyhow::Error with ❌ prefix
  • Immediate Return: Returns the error immediately from the function
  • Function Exit: Stops execution at the point of the macro call
  • Clean Code: Reduces boilerplate for error handling

§Use Cases

§Input Validation

use anyhow::Result;
use kasl::{msg_bail_anyhow, libs::messages::Message};

fn process_task(task_id: Option<i32>) -> Result<()> {
    let id = match task_id {
        Some(id) => id,
        None => msg_bail_anyhow!(Message::InvalidInput),
    };

    // Continue processing with valid ID
    let _ = id;
    Ok(())
}

§Permission Checking

use anyhow::Result;
use kasl::{msg_bail_anyhow, libs::messages::Message};

fn secure_operation() -> Result<()> {
    if !user_has_permission() {
        msg_bail_anyhow!(Message::PermissionDenied);
    }

    // Continue with authorized operation
    Ok(())
}

§Resource Validation

use anyhow::Result;
use kasl::{msg_bail_anyhow, libs::messages::Message};

fn access_resource(path: &str) -> Result<()> {
    if !resource_exists(path) {
        msg_bail_anyhow!(Message::FileNotFound);
    }

    // Continue with valid resource
    Ok(())
}

§Code Style Benefits

  • Reduced Boilerplate: Eliminates repetitive error handling code
  • Clear Intent: Makes error conditions immediately obvious
  • Consistent Errors: All bail errors have consistent formatting
  • Maintainability: Easier to update error handling patterns