[][src]Macro adhocerr::err

macro_rules! err {
    ($msg:literal) => { ... };
    ($fmt:literal, $($arg:tt)*) => { ... };
}

Create an ad-hoc error type with zero size if none is needed

Examples

Creating a static ad-hoc error type:

use adhocerr::err;

fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> {
    start
        .ancestors()
        .find(|a| a.join(".git").is_dir())
        .map(Path::to_owned)
        .ok_or(err!("Unable to find .git/ in parent directories"))
}

Which expands to:

fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> {
    start
        .ancestors()
        .find(|a| a.join(".git").is_dir())
        .map(Path::to_owned)
        .ok_or({
            #[derive(Debug)]
            struct AdhocError;

            impl std::error::Error for AdhocError {
                fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                    None
                }
            }

            impl core::fmt::Display for AdhocError {
                fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                    f.write_str("Unable to find .git/ in parent directories")
                }
            }

            AdhocError
        })
}

Creating a dynamic ad-hoc error type:

use adhocerr::err;

fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> {
    start
        .ancestors()
        .find(|a| a.join(".git").is_dir())
        .map(Path::to_owned)
        .ok_or(err!(
            "Unable to find .git/ in parent directories for {}",
            start.display()
        ))
}

Which expands to:

fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> {
    start
        .ancestors()
        .find(|a| a.join(".git").is_dir())
        .map(Path::to_owned)
        .ok_or(adhocerr::private::format_err(format_args!(
            "Unable to find .git/ in parent directories for {}",
            start.display()
        )))
}