metadata-gen 0.0.2

A powerful Rust library for extracting, validating, and processing metadata in YAML, TOML, and JSON formats from any content or data file.
Documentation
// src/examples/error_example.rs
#![allow(missing_docs)]

use metadata_gen::{
    error::MetadataError, extract_and_prepare_metadata,
    utils::async_extract_metadata_from_file,
};

/// Entry point for the metadata-gen error handling examples.
///
/// This function runs various examples demonstrating error creation, conversion,
/// and handling for different scenarios in the metadata-gen library.
///
/// # Errors
///
/// Returns an error if any of the example functions fail.
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("\n๐Ÿงช metadata-gen Error Handling Examples\n");

    extraction_error_example()?;
    processing_error_example()?;
    missing_field_error_example()?;
    date_parse_error_example()?;
    yaml_error_example()?;
    json_error_example()?;
    toml_error_example()?;
    unsupported_format_error_example()?;
    validation_error_example()?;
    io_error_example().await?;

    println!(
        "\n๐ŸŽ‰ All error handling examples completed successfully!"
    );

    Ok(())
}

/// Demonstrates handling of extraction errors.
fn extraction_error_example() -> Result<(), MetadataError> {
    println!("๐Ÿฆ€ Extraction Error Example");
    println!("---------------------------------------------");

    let invalid_content = "This content has no metadata";
    match extract_and_prepare_metadata(invalid_content) {
        Ok(_) => {
            println!("    โŒ Unexpected success in extracting metadata")
        }
        Err(e) => {
            println!(
                "    โœ… Successfully caught Extraction Error: {}",
                e
            );
        }
    }

    Ok(())
}

/// Demonstrates handling of processing errors.
fn processing_error_example() -> Result<(), MetadataError> {
    println!("\n๐Ÿฆ€ Processing Error Example");
    println!("---------------------------------------------");

    let error = MetadataError::new_processing_error(
        "Failed to process metadata",
    );
    println!("    โœ… Created Processing Error: {}", error);

    Ok(())
}

/// Demonstrates handling of missing field errors.
fn missing_field_error_example() -> Result<(), MetadataError> {
    println!("\n๐Ÿฆ€ Missing Field Error Example");
    println!("---------------------------------------------");

    let error = MetadataError::MissingFieldError("title".to_string());
    println!("    โœ… Created Missing Field Error: {}", error);

    Ok(())
}

/// Demonstrates handling of date parse errors.
fn date_parse_error_example() -> Result<(), MetadataError> {
    println!("\n๐Ÿฆ€ Date Parse Error Example");
    println!("---------------------------------------------");

    let error = MetadataError::DateParseError(
        "Invalid date format".to_string(),
    );
    println!("    โœ… Created Date Parse Error: {}", error);

    Ok(())
}

/// Demonstrates handling of YAML parsing errors.
fn yaml_error_example() -> Result<(), MetadataError> {
    println!("\n๐Ÿฆ€ YAML Error Example");
    println!("---------------------------------------------");

    let invalid_yaml = "invalid: yaml: data";
    let result: Result<serde_yml::Value, _> =
        serde_yml::from_str(invalid_yaml);

    match result {
        Ok(_) => println!(
            "    โŒ Unexpected success in parsing invalid YAML"
        ),
        Err(e) => {
            let error = MetadataError::YamlError(e);
            println!(
                "    โœ… Successfully caught YAML Error: {}",
                error
            );
        }
    }

    Ok(())
}

/// Demonstrates handling of JSON parsing errors.
fn json_error_example() -> Result<(), MetadataError> {
    println!("\n๐Ÿฆ€ JSON Error Example");
    println!("---------------------------------------------");

    let invalid_json = "{ invalid json }";
    match serde_json::from_str::<serde_json::Value>(invalid_json) {
        Ok(_) => println!(
            "    โŒ Unexpected success in parsing invalid JSON"
        ),
        Err(e) => {
            let error = MetadataError::JsonError(e);
            println!(
                "    โœ… Successfully caught JSON Error: {}",
                error
            );
        }
    }

    Ok(())
}

/// Demonstrates handling of TOML parsing errors.
fn toml_error_example() -> Result<(), MetadataError> {
    println!("\n๐Ÿฆ€ TOML Error Example");
    println!("---------------------------------------------");

    let invalid_toml = "invalid = toml data";
    match toml::from_str::<toml::Value>(invalid_toml) {
        Ok(_) => println!(
            "    โŒ Unexpected success in parsing invalid TOML"
        ),
        Err(e) => {
            let error = MetadataError::TomlError(e);
            println!("    โœ… Successfully caught TOML Error:");
            println!("    {}", error);

            // Print additional details about the error
            if let MetadataError::TomlError(ref toml_error) = error {
                println!("\n    ๐Ÿ“ Error details:");
                // Split the error message into lines for better formatting
                for line in toml_error.to_string().lines() {
                    println!("       {}", line);
                }

                // Add a suggestion
                println!("\n    ๐Ÿ’ก Suggestion:");
                println!("       Try enclosing the value in quotes:");
                println!("       invalid = \"toml data\"");
            }
        }
    }

    Ok(())
}

/// Demonstrates handling of unsupported format errors.
fn unsupported_format_error_example() -> Result<(), MetadataError> {
    println!("\n๐Ÿฆ€ Unsupported Format Error Example");
    println!("---------------------------------------------");

    let error =
        MetadataError::UnsupportedFormatError("XML".to_string());
    println!("    โœ… Created Unsupported Format Error: {}", error);

    Ok(())
}

/// Demonstrates handling of validation errors.
fn validation_error_example() -> Result<(), MetadataError> {
    println!("\n๐Ÿฆ€ Validation Error Example");
    println!("---------------------------------------------");

    let error = MetadataError::new_validation_error(
        "title",
        "Title must not be empty",
    );
    println!("    โœ… Created Validation Error: {}", error);

    Ok(())
}

/// Demonstrates handling of I/O errors.
async fn io_error_example() -> Result<(), MetadataError> {
    println!("\n๐Ÿฆ€ I/O Error Example");
    println!("---------------------------------------------");

    match async_extract_metadata_from_file("nonexistent_file.md").await
    {
        Ok(_) => println!(
            "    โŒ Unexpected success in reading nonexistent file"
        ),
        Err(e) => {
            println!("    โœ… Successfully caught I/O Error: {}", e);
        }
    }

    Ok(())
}