Crate propagate[][src]

Expand description

Error propagation tracing in Rust.

This crate provides propagate::Result, a replacement for the standard library result type that automatically tracks the propagation of error results using the ? operator.

Examples

Consider the following custom error type:

use std::io;

enum MyError {
    Unlucky,
    Io(io::Error),
    TooSmall(u64),
}

impl From<io::Error> for MyError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

The following two examples show how propagate::Result might be used for error handling.

With try blocks

This example makes use of try blocks. This makes the resulting code cleaner compared to not using try blocks.

#![feature(try_blocks)]
use std::fs::File;

fn file_size(path: &str) -> propagate::Result<u64, MyError> {
    try {
        // The `?` operator coerces `std::result::Result<_, io::Error>`
        // into `propagate::Result<_, MyError>`.
        let size = File::open(path)?.metadata()?.len();

        if size < 1024 {
            Err(MyError::TooSmall(size))?
        }

        size
    }
}

fn maybe_file_size(path: &str) -> propagate::Result<u64, MyError> {
    let lucky = (path.len() % 2) == 0;

    try {
        if !lucky {
            Err(MyError::Unlucky)?
        }

        file_size(path)?
    }
}

Without try blocks

This example is the same as the one above, except it does not make use of try blocks. This requires a bit more boilerplate, and also requires the user to remember to properly forward results (see propagate::Result for more information).

use propagate::ErrorTrace;
use std::fs::File;

fn file_size(path: &str) -> propagate::Result<u64, MyError> {
    // The `?` operator coerces `std::result::Result<_, io::Error>`
    // into `propagate::Result<_, MyError>`.
    let size = File::open(path)?.metadata()?.len();

    if size < 1024 {
        // Option 1: Coerce a `std::result::Result` to a `propagate::Result`
        // using `?`.
        Err(MyError::TooSmall(size))?
    }
     
    propagate::Ok(size)
}

fn maybe_file_size(path: &str) -> propagate::Result<u64, MyError> {
    let lucky = (path.len() % 2) == 0;

    if !lucky {
        // Option 2: Directly construct a `propagate::Result`
        // using `ErrorTrace::new()`.
        return propagate::Err(MyError::Unlucky, ErrorTrace::new())
    }
     
    // Must remember to surround with `Ok(..?)`.
    propagate::Ok(file_size(path)?)
}

See propagate::Result for more information.

Re-exports

pub use self::result::Result::Err;
pub use self::result::Result::Ok;

Modules

Defines a new result type.

Defines types for error tracing.

Structs

Represents a location (filename, line number) in the source code.

A stack of code locations forming an error trace.

Enums

A replacement for std::result::Result that supports tracing via the ? operator.

Traits

A trait denoting “stack-like” types that can be used with Result<T, E, S>.