Skip to main content

expect_error

Function expect_error 

Source
pub fn expect_error<T, E>(
    msg: impl Into<Cow<'static, str>>,
    body: impl FnOnce() -> Result<T, Frame>,
) -> Result<T, E>
where E: From<(Cow<'static, str>, Frame)>,
Expand description

Add context to errors, returning a custom error type.

§Type Parameters

  • T: The success type
  • E: 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?
examples/context.rs (lines 20-23)
19fn main() -> Result<(), Error> {
20    expect_error("This program will error", || {
21        connect("")?;
22        Ok(())
23    })
24}
More examples
Hide additional 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}