[][src]Crate snafu

SNAFU

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::{Snafu, ResultExt, Backtrace, ErrorCompat, ensure};
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

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.

Context

A combination of an underlying error and additional information about the error. It is not expected for users of this crate to interact with this type.

NoneError

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

Traits

ErrorCompat

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

OptionExt

Additions to Option.

ResultExt

Additions to Result.