Crate cotton[][src]

Expand description

Error context

Generally libraries should not add context to the errors as it may be considered sensitive for some uses. In this library context (like file paths) will be provided by default.

Static error types

When you need proper error handling (e.g. on the internal modules or when you need to act on the errors specifically) use standard way of doing this.

Use enums with Debug, Display and Error trait implementations. Add additional From implementations to make ? operator to work.

If you need to add context to an error you can use error_context crate that is included in the prelude.

Example custom static error type implementation

use cotton::prelude::*;

#[derive(Debug)]
enum FileResourceError {
        FileDigestError(PathBuf, FileDigestError),
        NotAFileError(PathBuf),
}

impl Display for FileResourceError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            // Do not include chained error message in the message; let the client handle this (e.g. with Problem type)
            FileResourceError::FileDigestError(path, _) => write!(f, "digest of a file {:?} could not be calculated", path),
            FileResourceError::NotAFileError(path) => write!(f, "path {:?} is not a file", path),
        }
    }
}

impl Error for FileResourceError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            // Chain the internal error
            FileResourceError::FileDigestError(_, err) => Some(err),
            FileResourceError::NotAFileError(_) => None,
        }
    }
}

// This allows for calls like `foo().wrap_error_while_with(|| self.path.clone())?` to add extra `PathBuf` context to the error
impl From<ErrorContext<FileDigestError, PathBuf>> for FileResourceError {
    fn from(err: ErrorContext<FileDigestError, PathBuf>) -> FileResourceError {
        FileResourceError::FileDigestError(err.context, err.error)
    }
}

Re-exports

pub use structopt;
pub use directories;
pub use filetime;
pub use boolinator;
pub use chrono;
pub use itertools;
pub use ansi_term;
pub use atty;
pub use log;
pub use problem;
pub use error_context;
pub use sha2;
pub use sha2::digest;
pub use sha2::digest::generic_array;
pub use hex;
pub use tap;
pub use duct;
pub use maybe_string;
pub use file_mode;
pub use shellwords;
pub use secrecy;
pub use file_owner;
pub use scopeguard;
pub use signal_hook;

Modules

NOTE: This code is taken from loggerv crate (MIT license) and modified.