[][src]Crate snafu

SNAFU

SNAFU is a library to easily assign underlying errors into domain-specific errors while adding context. For detailed information, please see the user's guide.

Quick example

This example mimics a (very poor) authentication process that opens a file, writes to a file, and checks the user's ID. While two of our operations involve an io::Error, these are different conceptual errors to us.

SNAFU creates context selectors mirroring each error variant. These are used with the context method to provide ergonomic error handling.

use snafu::{ensure, Backtrace, ErrorCompat, ResultExt, Snafu};
use std::{
    fs,
    path::{Path, PathBuf},
};

#[derive(Debug, Snafu)]
enum Error {
    #[snafu(display("Could not open config from {}: {}", filename.display(), source))]
    OpenConfig {
        filename: PathBuf,
        source: std::io::Error,
    },
    #[snafu(display("Could not save config to {}: {}", filename.display(), source))]
    SaveConfig {
        filename: PathBuf,
        source: std::io::Error,
    },
    #[snafu(display("The user id {} is invalid", user_id))]
    UserIdInvalid { user_id: i32, backtrace: Backtrace },
}

type Result<T, E = Error> = std::result::Result<T, E>;

fn log_in_user<P>(config_root: P, user_id: i32) -> Result<bool>
where
    P: AsRef<Path>,
{
    let config_root = config_root.as_ref();
    let filename = &config_root.join("config.toml");

    let config = fs::read(filename).context(OpenConfig { filename })?;
    // Perform updates to config
    fs::write(filename, config).context(SaveConfig { filename })?;

    ensure!(user_id == 42, UserIdInvalid { user_id });

    Ok(true)
}

fn log_in() {
    match log_in_user(CONFIG_DIRECTORY, USER_ID) {
        Ok(true) => println!("Logged in!"),
        Ok(false) => println!("Not logged in!"),
        Err(e) => {
            eprintln!("An error occurred: {}", e);
            if let Some(backtrace) = ErrorCompat::backtrace(&e) {
                println!("{}", backtrace);
            }
        }
    }
}

Re-exports

pub use snafu_derive::Snafu;

Modules

futures

Additions to the TryFuture and TryStream traits.

futures01

Additions to the Futures 0.1 Future and Stream traits.

guide

SNAFU user's guide

Macros

ensure

Ensure a condition is true. If it is not, return from the function with an error.

Structs

Backtrace

A backtrace starting from the beginning of the thread.

NoneError

A temporary error type used when converting an Option into a Result

Traits

AsErrorSource

Converts the receiver into an Error trait object, suitable for use in Error::source.

ErrorCompat

Backports changes to the Error trait to versions of Rust lacking them.

IntoError

Combines an underlying error with additional information about the error.

OptionExt

Additions to Option.

ResultExt

Additions to Result.