pub trait Context:
Display
+ Debug
+ Send
+ Sync
+ 'static { }
Expand description
Defines the current context of a Report
.
When in a std
environment or on a nightly toolchain, every Error
is a valid Context
.
This trait is not limited to Error
s and can also be manually implemented on a type.
§Example
Used for creating a Report
or for switching the Report
’s context:
use std::{fmt, fs, io};
use error_stack::{Context, Result, ResultExt, Report};
#[derive(Debug)]
pub enum ConfigError {
ParseError,
}
impl fmt::Display for ConfigError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
...
}
}
// In this scenario, `Error` is not implemented for `ConfigError` for some reason, so implement
// `Context` manually.
impl Context for ConfigError {}
pub fn read_file(path: &str) -> Result<String, io::Error> {
// Creates a `Report` from `io::Error`, the current context is `io::Error`
fs::read_to_string(path).map_err(Report::from)
}
pub fn parse_config(path: &str) -> Result<Config, ConfigError> {
// The return type of `parse_config` requires another context. By calling `change_context`
// the context may be changed.
read_file(path).change_context(ConfigError::ParseError)?;
...
}