1 个不稳定版本
0.0.0-预留 | 2022 年 8 月 24 日 |
---|
#126 在 #report
6KB
error-stack
error-stack
是一个支持任意附加用户数据的上下文感知错误处理库。
请阅读我们关于其起源故事的公告帖子。
该库允许在错误传播时围绕错误构建一个 Report
use std::fmt;
use error_stack::{Context, IntoReport, Report, Result, ResultExt};
#[derive(Debug)]
struct ParseExperimentError;
impl fmt::Display for ParseExperimentError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("invalid experiment description")
}
}
impl Context for ParseExperimentError {}
fn parse_experiment(description: &str) -> Result<(u64, u64), ParseExperimentError> {
let value = description
.parse()
.into_report()
.attach_printable_lazy(|| format!("{description:?} could not be parsed as experiment"))
.change_context(ParseExperimentError)?;
Ok((value, 2 * value))
}
#[derive(Debug)]
struct ExperimentError;
impl fmt::Display for ExperimentError {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("Experiment error: Could not run experiment")
}
}
impl Context for ExperimentError {}
fn start_experiments(
experiment_ids: &[usize],
experiment_descriptions: &[&str],
) -> Result<Vec<u64>, ExperimentError> {
let experiments = experiment_ids
.iter()
.map(|exp_id| {
let description = experiment_descriptions.get(*exp_id).ok_or_else(|| {
Report::new(ExperimentError)
.attach_printable(format!("Experiment {exp_id} has no valid description"))
})?;
let experiment = parse_experiment(description)
.attach_printable(format!("Experiment {exp_id} could not be parsed"))
.change_context(ExperimentError)?;
Ok(move || experiment.0 * experiment.1)
})
.collect::<Result<Vec<_>, ExperimentError>>()
.attach_printable("Unable to set up experiments")?;
Ok(experiments.iter().map(|experiment| experiment()).collect())
}
fn main() -> Result<(), ExperimentError> {
let experiment_ids = &[0, 2];
let experiment_descriptions = &["10", "20", "3o"];
start_experiments(experiment_ids, experiment_descriptions)?;
Ok(())
}
这很可能会导致错误并打印
请参阅文档以获取完整描述。