Error

Enum Error 

Source
pub enum Error {
    Io(Error),
    Network(Error),
    Parse(String),
    Index(String),
    Storage(String),
    Config(String),
    NotFound(String),
    InvalidUrl(String),
    ResourceLimited(String),
    Timeout(String),
    Serialization(String),
    Other(String),
}
Expand description

The main error type for blz-core operations.

All public functions in blz-core return Result<T, Error> for consistent error handling. The error type includes automatic conversion from common standard library errors and provides additional metadata for error handling logic.

§Error Source Chain

Errors maintain the full error chain through the source() method, allowing for detailed error inspection and debugging.

§Display vs Debug

  • Display provides user-friendly error messages
  • Debug includes full error details and source chain information

Variants§

§

Io(Error)

I/O operation failed.

Covers file system operations like reading/writing files, creating directories, checking file permissions, etc. The underlying std::io::Error is preserved to maintain detailed error information.

§Recoverability

Some I/O errors are recoverable (timeouts, interruptions), while others are permanent (permission denied, file not found).

§

Network(Error)

Network operation failed.

Covers HTTP requests for fetching llms.txt files, checking ETags, and other network operations. The underlying reqwest::Error is preserved for detailed connection information.

§Recoverability

Connection and timeout errors are typically recoverable, while authentication and malformed URL errors are permanent.

§

Parse(String)

Parsing operation failed.

Occurs when markdown content cannot be parsed, TOML/JSON deserialization fails, or content doesn’t match expected format.

§Common Causes
  • Malformed markdown syntax
  • Invalid TOML configuration
  • Unexpected content structure
  • Character encoding issues
§

Index(String)

Search index operation failed.

Covers failures in creating, updating, or querying the search index. This includes Tantivy-related errors and index corruption.

§Common Causes
  • Index corruption
  • Disk space exhaustion during indexing
  • Invalid search queries
  • Schema version mismatches
§

Storage(String)

Storage operation failed.

Covers cache storage operations beyond basic file I/O, such as managing archived versions, checksum validation, and cache consistency.

§Common Causes
  • Cache corruption
  • Concurrent access conflicts
  • Checksum mismatches
  • Archive management failures
§

Config(String)

Configuration is invalid or inaccessible.

Occurs when configuration files are malformed, contain invalid values, or cannot be accessed due to permissions or path issues.

§Common Causes
  • Invalid TOML syntax in config files
  • Missing required configuration fields
  • Configuration values outside valid ranges
  • Config directory creation failures
§

NotFound(String)

Requested resource was not found.

Used for missing files, non-existent sources, or requested content that doesn’t exist in the cache.

§Common Causes
  • Requested source alias doesn’t exist
  • File was deleted after being indexed
  • Cache was cleared but references remain
§

InvalidUrl(String)

URL is malformed or invalid.

Occurs when URLs provided for llms.txt sources cannot be parsed or contain invalid characters/schemes.

§Common Causes
  • Malformed URLs in configuration
  • Unsupported URL schemes
  • Invalid characters in URLs
§

ResourceLimited(String)

Resource limit was exceeded.

Used when operations exceed configured limits such as memory usage, file size, or processing time constraints.

§Common Causes
  • Document exceeds maximum size limit
  • Memory usage exceeds configured threshold
  • Too many concurrent operations
§

Timeout(String)

Operation timed out.

Used for operations that exceed their configured timeout duration. This is typically recoverable with retry logic.

§Common Causes
  • Network request timeouts
  • Long-running parsing operations
  • Index operations on large documents
§

Serialization(String)

Serialization or deserialization failed.

Occurs when converting between data formats (JSON, TOML, binary) fails due to incompatible formats or corruption.

§Common Causes
  • JSON/TOML syntax errors
  • Schema version mismatches
  • Data corruption
  • Incompatible format versions
§

Other(String)

Generic error for uncategorized failures.

Used for errors that don’t fit other categories or for wrapping third-party errors that don’t have specific mappings.

Implementations§

Source§

impl Error

Source

pub fn is_recoverable(&self) -> bool

Check if the error might be recoverable through retry logic.

Returns true for errors that are typically temporary and might succeed if the operation is retried after a delay. This includes network timeouts, connection failures, and temporary I/O issues.

§Returns
  • true for potentially recoverable errors (timeouts, connection issues)
  • false for permanent errors (parse failures, invalid configuration)
§Examples
use blz_core::{Error, Result};
use std::io;

let recoverable_errors = vec![
    Error::Timeout("Request timed out".to_string()),
    Error::Io(io::Error::new(io::ErrorKind::TimedOut, "timeout")),
    Error::Io(io::Error::new(io::ErrorKind::Interrupted, "interrupted")),
];

let permanent_errors = vec![
    Error::Parse("Invalid markdown".to_string()),
    Error::Config("Missing field".to_string()),
    Error::InvalidUrl("Not a URL".to_string()),
];

for error in recoverable_errors {
    assert!(error.is_recoverable());
}

for error in permanent_errors {
    assert!(!error.is_recoverable());
}
§Retry Strategy

When an error is recoverable, consider implementing exponential backoff:

use blz_core::{Error, Result};
use std::time::Duration;

async fn retry_operation<F, T>(mut op: F, max_attempts: u32) -> Result<T>
where
    F: FnMut() -> Result<T>,
{
    let mut attempts = 0;
    let mut delay = Duration::from_millis(100);

    loop {
        match op() {
            Ok(result) => return Ok(result),
            Err(e) if e.is_recoverable() && attempts < max_attempts => {
                attempts += 1;
                tokio::time::sleep(delay).await;
                delay *= 2; // Exponential backoff
            }
            Err(e) => return Err(e),
        }
    }
}

// Example usage:
// let result = retry_operation(|| fetch_document(), 3).await?;
Source

pub const fn category(&self) -> &'static str

Get the error category as a string identifier.

Returns a static string that categorizes the error type for logging, metrics collection, and error handling logic. This is useful for grouping errors in monitoring systems or implementing category-specific error handling.

§Returns

A static string representing the error category:

  • "io" - File system and I/O operations
  • "network" - HTTP requests and network operations
  • "parse" - Content parsing and format conversion
  • "index" - Search index operations
  • "storage" - Cache storage and management
  • "config" - Configuration and settings
  • "not_found" - Missing resources or files
  • "invalid_url" - URL format and validation
  • "resource_limited" - Resource constraints and limits
  • "timeout" - Operation timeouts
  • "serialization" - Data format conversion
  • "other" - Uncategorized errors
§Examples
use blz_core::Error;
use std::collections::HashMap;

// Track error counts by category
let mut error_counts: HashMap<String, u32> = HashMap::new();

fn record_error(error: &Error, counts: &mut HashMap<String, u32>) {
    let category = error.category().to_string();
    *counts.entry(category).or_insert(0) += 1;
}

// Usage in error handling
let errors = vec![
    Error::Parse("Invalid format".to_string()),
    Error::Config("Missing field".to_string()),
    Error::NotFound("Resource not found".to_string()),
];

for error in &errors {
    record_error(error, &mut error_counts);
}
§Structured Logging
use blz_core::Error;

fn log_error(error: &Error) {
    println!(
        "{{\"level\":\"error\",\"category\":\"{}\",\"message\":\"{}\"}}",
        error.category(),
        error
    );
}

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error

Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<Error> for Error

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(source: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for Error

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Error

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T> ToStringFallible for T
where T: Display,

Source§

fn try_to_string(&self) -> Result<String, TryReserveError>

ToString::to_string, but without panic on OOM.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> Fruit for T
where T: Send + Downcast,