pub fn expect_error<T, E>(
msg: impl Into<Cow<'static, str>>,
body: impl FnOnce() -> Result<T, Frame>,
) -> Result<T, E>Expand description
Add context to errors, returning a custom error type.
§Type Parameters
T: The success typeE: The custom error type
§Example
The simplest way to add context is using it with the ready to use
scoped_error::Error type when you don’t need a custom error type.
use scoped_error::{Error, expect_error};
fn read_file() -> Result<String, Error> {
expect_error("Failed to read configuration", || {
let cfg = std::fs::read_to_string("config.toml")?;
Ok(cfg)
})
}Use this function with custom error types that implement
From<(Cow<'static, str>, Frame)>. The impl_context_error!
macro generates this implementation for you.
use scoped_error::{expect_error, impl_context_error};
impl_context_error!(MyError);
fn do_work() -> Result<String, MyError> {
expect_error("Failed to do work", || {
let cfg = std::fs::read_to_string("config.toml")?;
Ok(cfg)
})
}