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)
})
}Examples found in repository?
More examples
examples/bail.rs (lines 8-13)
7fn connect(url: &str) -> Result<String, Error> {
8 expect_error("Failed to connect to target", || {
9 if !url.is_empty() {
10 return Ok("connected".to_string());
11 }
12 bail!("invalid URL [{}]", url);
13 })
14}
15
16fn main() -> Result<(), Error> {
17 expect_error("This program will error", || {
18 connect("")?;
19 Ok(())
20 })
21}