Skip to main content

Crate pi_result

Crate pi_result 

Expand description

§pi_result

pi_result 是一个基于 thiserror + error-stack 的 Rust 错误处理薄封装库。

它的目标不是重新发明错误框架,而是在保留 Rust 原生表达力的前提下,统一以下能力:

  • 对外稳定的 Result / Error 形态
  • 对内结构化、类型化、可匹配的错误建模
  • 跨模块、跨 crate、跨 App 的上下文叠加与错误冒泡
  • 面向调试、日志、测试和诊断的可观测错误栈
  • 统一暴露 thiserror 与 error-stack 的常用公共 API

当前仓库已完成基础类型层、边界传播层、互操作层、稳定观测层和导出层的 V1 实现,包括 kind、result、attachment、boundary、interop、inspect、fmt、testing、prelude。本文档中的 API 与示例会继续随着集成测试、doctest 和可能的 nightly 增强能力校准。 当前 README 中的示例按 3 类维护:

  • 可独立运行的入门示例,直接升级为 doctest 并纳入 cargo test
  • 复杂多层或异步示例,尽量升级为 rust,no_run,至少纳入编译验证
  • 纯说明性的类型别名片段,使用普通代码块展示,不进入 doctest

README 中的示例和 docs/ 中的用例图会作为单元测试、集成测试和必要 doctest 的重要来源,要求测试覆盖但不限于这些文档场景。 当前测试与 benchmark 已进一步覆盖:

  • README 示例 1-6
  • docs/ 中基础、中等复杂度、完整场景三类用例图
  • 10 层以上深链路传播
  • 32 / 64 / 128 层极深链路传播
  • 严格最坏模型:
    • 每层都执行 attach + attach_with + change_context
  • 深链路 trace 功能矩阵:
    • 无 trace
    • 仅 Backtrace
    • 仅 SpanTrace
    • Backtrace + SpanTrace
  • Backtrace 自动捕获
  • SpanTrace feature + ErrorLayer 捕获
  • 高频错误突发下的深链路上报开销
  • 256 / 1024 次极深链路突发上报
  • 控制变量 benchmark:
    • 纯 change_context 深度成本
    • 静态 attach 数量成本
    • 动态 attach_with 数量成本

性能与行为评估当前以 Linux 生产环境为基线;Windows 开发环境的测试结果仅作为开发期参考,不作为最终性能结论。

§文档索引

§快速开始与兼容派生(Quick Start and Compatible Derive)

本节从最小错误(minimal error)到跨库接入(cross-crate integration)说明错误派生(error derive)。 普通业务代码(business code)推荐 use pi_result::prelude::*; 和 #[derive(Debug, ThisError)]: ThisError 是派生宏(derive macro),Error 是默认报告别名(report alias),两者职责不同。 不要把 use pi_result::thiserror::Error; 当作普通推荐导入(recommended import); 它是保留的兼容入口(compatibility entry),会引入名为 Error 的宏(macro),也容易与报告名称(report name)混淆。 只有名称冲突或明确兼容需求(name conflict/compatibility requirement)时,才选用显式导入或完整路径(explicit import/full path)。

下游(downstream)只需要 pi_result,不必额外声明 thiserror 或 pi_result_macros 依赖(dependencies)。 下面的相容版本范围(compatible version range)不是补丁固定(patch pin); 实际使用的发布版本(published version)必须已经包含本节修复(fix)。 本节不表示任何旧的 0.1.x 发布包(published package)都会自动获得新实现(implementation)。 若锁文件(lockfile)仍选中旧包(older package),应在包含修复的版本发布后更新对应依赖(dependency); 增加导入(import)不能修复旧宏生成的不可达支持路径(unreachable generated support path)。

§示例 1:仅依赖主库的最小错误(Runtime-Only Minimal Error)

完整的 Cargo.toml:

[package]
name = "error_demo"
version = "0.1.0"
edition = "2021"

[dependencies]
pi_result = "0.1"

src/main.rs:

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[error("invalid request: {0}")]
struct InvalidRequest(u32);

fn main() {
    let error = InvalidRequest(7);
    let _: &dyn std::error::Error = &error;
    assert_eq!(error.to_string(), "invalid request: 7");
}

派生(derive)生成标准 Error/Display 实现(implementations),不创建新的运行期包装(runtime wrapper), 也不自动把错误(error)放进 Report。局部返回值(local return value)仍可使用 RawResult<T, InvalidRequest>; 需要上下文与附件(context/attachments)时,再进入报告链(report chain)。

§示例 2:来源、转换、透明与报告链(Source, From, Transparency and Reports)

#[from] 生成同层转换(same-layer conversion),同时把该字段作为标准来源(standard source); #[source] 只指定来源(source),不会生成转换(conversion)。 #[error(transparent)] 委托内部错误的显示及来源(inner-error Display/source),不是额外插入一层来源(source layer)。 以下示例(example)不访问文件(files),用确定的 I/O 错误(I/O error)验证完整链条(complete chain):

use pi_result::prelude::*;
use std::error::Error as StdError;

#[derive(Debug, ThisError)]
#[error("read failed: {source}")]
struct ReadError {
    #[from]
    source: std::io::Error,
}

#[derive(Debug, ThisError)]
#[error(transparent)]
struct Transparent(ReadError);

#[derive(Debug, ThisError)]
#[error("outer {cause}")]
struct WithSource {
    #[source]
    cause: ReadError,
}

#[derive(Debug, ThisError)]
#[error("configuration load failed")]
struct LoadContext;

fn read() -> RawResult<(), ReadError> {
    Err::<(), _>(std::io::Error::from(std::io::ErrorKind::NotFound))?;
    Ok(())
}

fn load() -> Result<()> {
    read()
        .attach(Operation("read_config"))
        .into_typed(LoadContext)
        .into_error(ErrorKind::Io)?;
    Ok(())
}

fn main() {
    let report = load().expect_err("deterministic I/O failure");
    assert_eq!(report.current_kind(), &ErrorKind::Io);
    assert!(report.contains_context::<ReadError>());
    assert!(report.contains_context::<LoadContext>());
    assert_eq!(report.attachment_ref::<Operation>(), Some(&Operation("read_config")));

    let read = report.downcast_ref::<ReadError>().expect("original typed error");
    assert!(std::ptr::eq(
        read.source().unwrap().downcast_ref::<std::io::Error>().unwrap(),
        &read.source,
    ));

    let wrapped = Transparent(std::io::Error::from(std::io::ErrorKind::NotFound).into());
    assert_eq!(wrapped.to_string(), wrapped.0.to_string());
    assert!(std::ptr::eq(
        wrapped.source().unwrap().downcast_ref::<std::io::Error>().unwrap(),
        &wrapped.0.source,
    ));

    let outer = WithSource { cause: std::io::Error::from(std::io::ErrorKind::NotFound).into() };
    assert!(std::ptr::eq(
        outer.source().unwrap().downcast_ref::<ReadError>().unwrap(),
        &outer.cause,
    ));
}

公开签名(public signature)仍是 Result<()>;内部错误、解释视角及附件(internal error/context/attachment)没有因派生入口(derive entry)改变而丢失。 ? 不会猜测公共分类(public classification):从裸错误(raw error)进入公共报告(public report)时,仍在边界(boundary)显式使用 into_typed/into_error。

§示例 3:泛型、借用与局部非线程安全错误(Generics, Borrows and Local Errors)

派生宏(derive macro)不对整个错误(whole error)额外增加 Send/Sync/'static 约束(bounds)。 合法借用(valid borrows)及局部 Rc 错误(local errors)可以实现标准 Error; 但这不改变 Report::new 对接纳数据(accepted data)的线程安全与寿命要求(thread-safety/lifetime requirements)。

use pi_result::prelude::*;
use std::{cell::Cell, fmt, rc::Rc};

#[derive(Debug, ThisError)]
#[error("{label}: {value}")]
struct Described<'a, T>
where
    T: fmt::Display + fmt::Debug,
{
    label: &'a str,
    value: T,
}

#[derive(Debug, ThisError)]
#[error("computed {}", .0 + 1)]
struct Computed(u8);

#[derive(Debug, ThisError)]
#[error("local {0:?}")]
struct Local(Rc<Cell<u8>>);

fn main() {
    let label = String::from("borrowed");
    assert_eq!(Described { label: &label, value: 7 }.to_string(), "borrowed: 7");
    assert_eq!(Computed(3).to_string(), "computed 4");
    let local = Local(Rc::new(Cell::new(3)));
    local.0.set(4);
    let _: &dyn std::error::Error = &local;
    assert_eq!(local.0.get(), 4);
}

下面应当拒绝编译(compile rejection),不能以派生成功(derive success)推断报告可跨线程(cross-thread report):

ⓘ
use pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[error("local")]
struct Local(std::rc::Rc<u8>);

let _ = Report::new(Local(std::rc::Rc::new(1)));

如果必须把这类外部错误(external error)并入报告链(report chain), 使用后文的 ExternalError 快照适配(snapshot adaptation),不要强制添加不成立的线程安全保证(thread-safety guarantee)。 自定义格式表达式(custom format expression)仍遵循原派生语法(derive syntax);它在实际格式化(formatting)时运行, 派生宏(derive macro)不会在编译期执行这些业务表达式(compile-time business-expression execution)。

§示例 4:重命名直接依赖(Renamed Direct Dependency)

完整清单(manifest):

[package]
name = "derive_renamed"
version = "0.0.0"
edition = "2021"

[dependencies]
errors = { package = "pi_result", version = "0.1" }

完整 src/main.rs 如下(代码块(code block)依赖上述真实别名清单(alias manifest),不使用文档测试的隐藏替代别名(doctest-only substitute alias)):

use errors::prelude::*;

#[derive(Debug, ThisError)]
#[error("renamed")]
struct Automatic;

#[derive(Debug, ThisError)]
#[pi_result(crate = ::errors)]
#[error("selected")]
struct Selected;

fn main() {
    assert_eq!(Automatic.to_string(), "renamed");
    assert_eq!(Selected.to_string(), "selected");
    let report: Error = Report::new(Automatic).change_context(ErrorKind::Other);
    assert!(report.contains_context::<Automatic>());
}

普通单一直接依赖(single direct dependency)自动发现(automatic discovery)实际名字(actual name),不必加覆盖属性(override attribute)。 #[pi_result(crate = ::errors)] 是可选的明确选择(explicit selection),应放在引入辅助属性(helper attribute)的 derive 之后。 它接收 Rust 路径(path),不是字符串(string),也不是 __derive_support_v1 模块路径(module path)。

§示例 5:App 仅依赖桥接库(Bridge-Only App Dependency)

当 App 通过另一库重导出(re-export)访问 pi_result,自动依赖发现(automatic dependency discovery)不能推断这种间接关系(indirect relationship)。 假设 bridge/ 与 app/ 是同级目录(sibling directories)。桥接库(bridge crate)的 bridge/Cargo.toml:

[package]
name = "derive_bridge"
version = "0.0.0"
edition = "2021"

[dependencies]
pi_result = "0.1"

bridge/src/lib.rs:

pub use pi_result;
pub use pi_result::prelude;

App 的 app/Cargo.toml:

[package]
name = "derive_app"
version = "0.0.0"
edition = "2021"

[dependencies]
bridge = { package = "derive_bridge", path = "../bridge" }

app/src/main.rs:

use bridge::pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[pi_result(crate = ::bridge::pi_result)]
#[error("indirect {0}")]
struct Indirect(u8);

fn main() {
    assert_eq!(Indirect(7).to_string(), "indirect 7");
    let report = Report::new(Indirect(7)).change_context(ErrorKind::Dependency);
    assert!(report.contains_context::<Indirect>());
}

App 没有额外依赖 pi_result、thiserror 或宏包(macro package)。 显式路径(explicit path)必须在派生位置可达且可见(reachable/visible at derive site),并指向提供相容支持协议(compatible support protocol)的主库根(runtime-crate root)。 不写该属性(attribute)的间接用法(indirect usage)会给出依赖发现失败(dependency-discovery failure),不会猜测或静默使用上游宏(guessed path/silent upstream-macro fallback)。

§示例 6:旧入口兼容与名称冲突(Legacy Entry and Name Conflicts)

旧路径(legacy path)保留,下面仅演示兼容(compatibility),不是普通推荐写法(recommended usage):

use pi_result::prelude::*;

#[derive(Debug, pi_result::thiserror::Error)]
#[pi_result(crate = ::pi_result)]
#[error("legacy")]
struct Legacy;

#[derive(Debug, pi_result::ThisError)]
#[pi_result(crate = ::pi_result)]
#[error("root")]
struct Root;

fn main() {
    assert_eq!(Legacy.to_string(), "legacy");
    assert_eq!(Root.to_string(), "root");
    let report: Error = Report::new(Legacy).change_context(ErrorKind::Other);
    assert!(report.contains_context::<Legacy>());
}

上述旧入口(legacy entry)识别新增 #[pi_result(...)],证明它也使用本库兼容派生(compatible derive),不是仍指向原版宏(upstream macro)。 遇到真正名称冲突(name conflict)时,可以显式使用 pi_result::prelude::ThisError, 或将该宏重命名(macro renaming);无需重新引入 thiserror 依赖(dependency)。

§示例 7:显式选择、错误配置与版本边界(Explicit Selection and Version Boundaries)

显式覆盖(explicit override)只选择合法、可达的 Rust 库路径(crate path),不是另一套 Cargo 依赖解析(dependency resolution)。 下面使用同一主库(runtime crate)的合法名称别名(name alias),不虚构不存在的双版本清单(nonexistent dual-version manifest):

extern crate pi_result as selected_errors;
use pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[pi_result(crate = ::selected_errors)]
#[error("selected")]
struct Selected;

fn main() {
    assert_eq!(Selected.to_string(), "selected");
    let report: Error = Report::new(Selected).change_context(ErrorKind::Other);
    assert!(report.contains_context::<Selected>());
}

多别名、多个实际版本或间接门面(multiple aliases/versions/indirect facades)并存时,应明确选择目标(target),不要把自动发现结果(automatic-discovery result)当成调用者意图(caller intent)。 覆盖属性(override attribute)不能使 Cargo 本来不接受的依赖组合(dependency combination)合法, 不能创造尚未发布的版本(unpublished version),也不能使不相容的支持协议(incompatible support protocol)相容。 不同 Cargo 库包身份(package identities)产生的 ErrorKind/Report 类型(types)也不会因名字相同而自动成为同一类型(same type)。

这些配置(configurations)必须失败(fail),不会静默忽略(silently ignore):

ⓘ
use pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[pi_result(crate = "pi_result")]
#[error("bad path")]
struct BadPath;
ⓘ
use pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[pi_result(crate = ::not_a_dependency)]
#[error("missing target")]
struct MissingTarget;

重复属性、未知键、路径泛型实参以及字段或变体位置(duplicate attributes/unknown keys/generic path arguments/field-variant placement)同样被拒绝(reject)。 合法语法路径(syntactically valid path)的目标存在性、可见性及协议成员(target existence/visibility/protocol members)最终由目标编译器(target compiler)检查(check)。 解析或路径失败(parse/path failure)直接保留原诊断(original diagnostic); 只有正常生成失败(normal-generation failure)才追加错误实现占位(error-implementation placeholders)。 占位(placeholder)始终伴随编译错误(compile error),不是成功恢复或业务运行期分支(successful recovery/business-runtime branch)。

§示例 8:夜间提供者与请求引用(Nightly Provider and Request Reference)

普通错误派生(ordinary error derive)不要求下游启用夜间特性(nightly feature)。 但派生类型(derived type)包含自动提供(automatic provision)的 Backtrace 时,生成的 Error::provide 使用不稳定标准接口(unstable standard interface); 目标库包自身(target crate itself)必须使用夜间工具链(nightly toolchain)并启用该语言特性(language feature)。 依赖库的特性属性(dependency feature attribute)不会传播到调用者(caller)。

以下是夜间目标(nightly target)的完整 src/main.rs;清单(manifest)仍使用示例 1 的唯一依赖(single dependency):

#![feature(error_generic_member_access)]

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[error("provided")]
struct Provided {
    backtrace: std::backtrace::Backtrace,
}

fn main() {
    let error = Provided { backtrace: std::backtrace::Backtrace::disabled() };
    let trace = std::error::request_ref::<std::backtrace::Backtrace>(&error)
        .expect("provided reference");
    assert!(std::ptr::eq(trace, &error.backtrace));
}

这里刻意使用禁用回溯对象(disabled backtrace):验证提供者引用身份(provider-reference identity),没有执行回溯采集(backtrace capture)。 std::error::request_ref 读取提供者借出的引用(provided reference),不是遍历所有报告帧(report frames); 任意提供值(provided values)的 request_value 以及报告级(report-level)request_refs/request_values,见后文夜间观测(nightly inspection)示例。 如果只需要附件(attachments),优先使用稳定版 attach/downcast_ref,不为此开启语言不稳定特性(unstable language feature)。 pi_result 仍自动探测自身工具链(toolchain detection),没有新增需要手动打开的 nightly Cargo 特性(feature); 上述目标语言特性(target language feature)与这个自动探测(automatic detection)是两个边界(boundaries)。

§本轮保持项、变化与维护边界(Compatibility and Maintenance Boundaries)

对象(Object)保持或变化(Preserved or Changed)使用注意(Usage Boundary)
Result<T, C = ErrorKind>、TypedResult、RawResult、ErrorReport、Error、ErrorKind名称、泛型参数及默认值、类型身份(names/generic parameters-defaults/type identities)保持没有新错误容器(error container)或运行期转换层(runtime conversion layer)
?、attach/attach_with、change_context、into_typed/into_error 与观测(inspection)原传播、分类及观测语义(propagation/classification/inspection semantics)保持原上下文与附件约束(context/attachment bounds)不放宽
prelude::ThisError、根 ThisError、pi_result::thiserror::Error名称路径(name paths)保持,宏提供者身份(macro-provider identity)改变普通代码(ordinary code)推荐预导入(prelude);旧路径(legacy path)仍可用
pi_result::thiserror从上游库重导出(upstream-crate re-export)变为同名内联门面(inline facade)其余上游公共名称(upstream public names)继续导出;不声称模块定义身份(module-definition identity)不变
生成支持路径(generated support path)改为所选主库的 __derive_support_v1与上游补丁编号(upstream patch number)无关;该隐藏协议(hidden protocol)不是建议手写业务代码(handwritten business code)的接口(API)
#[pi_result(crate = ...)]新增可选容器属性(optional container attribute)普通直接依赖(ordinary direct dependency)不必添加;不重写用户类型、表达式或字符串(user types/expressions/strings)
显示、来源、转换、泛型与提供者(Display/source/conversion/generics/provider)保持固定上游源码 2.0.21 的生成语义(generation semantics)及已说明的必要适配(necessary adaptations)上游未来增加的派生语法(future derive syntax)不会因依赖范围相容(compatible dependency range)自动进入本库维护分支(maintained fork)
错误配置诊断(configuration diagnostics)新增路径覆盖诊断(path-override diagnostics),配置校验(configuration validation)先于生成校验(generation validation)保留原解析/生成诊断(parse/generation diagnostics);不保证所有次生诊断(secondary diagnostics)消失
依赖与发布(dependencies/publishing)主库新增相容范围的配套宏依赖(companion macro dependency),仍保留 thiserror = "2.0"两包同仓库、分别发布(same repository/separate publishing);所需宏版本(macro version)须先可从注册表(registry)取得,发布(publication)由维护者操作(maintainer-operated)

过程宏(procedural macro)的定义位置与重导出位置(definition/re-export locations)不同,这与上游 thiserror-impl -> thiserror 的组织(organization)相同。 仅重导出(re-export)原版宏(upstream macro)不会重写其生成的 ::thiserror 支持引用(support references), 因而过去可能要求下游另加直接依赖(extra direct dependency)。 本库兼容派生(compatible derive)改用自有版本化支持协议(owned versioned support protocol),不是推断上游故意禁止封装(intentional encapsulation prohibition)。

编译期(compile time)仍有语法解析、令牌分配及可选的依赖发现(syntax parsing/token allocations/dependency discovery); 自动发现(automatic discovery)可能读清单、等待依赖缓存锁或启动 Cargo 子进程(manifest reads/dependency-cache lock/Cargo subprocess)。 显式路径(explicit path)跳过发现(discovery),但不代表整体无分配或固定耗时(zero allocation/fixed duration)。 本轮不增加业务运行期包装(business-runtime wrapper),也没有性能测量(performance measurement)证明本轮更快(faster)。 普通配置与语义失败(configuration/semantic failures)输出编译诊断(compile diagnostics); 不捕获编译器、依赖库恐慌或分配失败(compiler/dependency panic/allocation failure),不改变后文业务无手动恐慌风格(business panic-free style)的边界(boundary)。

验证映射(verification mapping):普通示例(ordinary examples)由文档测试(doctests)校验; 重命名、间接重导出、旧入口新属性和夜间提供者(renaming/indirect re-export/legacy-entry new attribute/nightly provider) 另由 tests/derive_reexports.rs 的真实独立下游(independent downstream)编译运行(compile/run), 并检查配置、缺失协议、非线程安全报告接纳及提供者特性门(configuration/missing protocol/non-Send-Sync report acceptance/provider feature gate)的拒绝编译(compile rejection)。 这些测试(tests)不在下游清单(downstream manifest)偷加 thiserror 或宏包(macro package), 也不把隐藏导入(hidden import)的文档片段(documentation snippet)当成真实 Cargo 名称发现(name discovery)证据。

§目标与非目标

§目标

pi_result 重点解决以下问题:

  1. 下层依赖库的内部错误变化,不应频繁污染上层公开 API。
  2. 库内部仍然需要保留强类型、可匹配、可演进的错误模型。
  3. 每一层调用者都应能补充自己的上下文后继续 ? 冒泡。
  4. 最终错误处理者应能读取:
    • 公共错误语义
    • 内部 typed error
    • 结构化 attachment
    • 可选 Backtrace / SpanTrace

§非目标

pi_result 不打算:

  1. 重新包装一个新的 Report 类型。
  2. 用重型宏 DSL 遮蔽 error-stack 原生语义。
  3. 强迫所有代码一开始就进入 report 链路。
  4. 把所有生态库都变成自己的无边界 re-export 面。

§核心概念

§LocalError

模块内部局部错误,通常用 thiserror 定义。

职责:

  • 叶子错误聚合
  • 同层静态 #[from] 转换
  • 内部精确匹配

§ErrorKind

公共稳定错误语义。

职责:

  • 作为公开 API 的默认错误解释视角
  • 屏蔽下层依赖错误的细粒度变化
  • 供最终处理者进行粗粒度分类

§Context

error-stack::Report<C> 的 C 表示“当前解释视角”。

它不是:

  • 根因全集
  • 所有错误类型的并集

§Attachment

附着在 Report 上的运行时上下文。

例如:

  • Operation
  • Stage
  • Module
  • PathAttachment
  • ResourceName
  • RetryCount

§Backtrace

原生代码调用栈回溯。

§SpanTrace

tracing span 的逻辑上下文轨迹。

§业务上下文链

通过 change_context、attach、attach_with 等显式构建的错误语义链。

这是 pi_result 最核心、最可控的可观测信息,不能被 Backtrace 或 SpanTrace 替代。

§暴露的类型形态

pi_result 计划暴露 4 种核心形态。

§pi_result::Result<T>

pub type Result<T> = core::result::Result<T, error_stack::Report<ErrorKind>>;

作用:

  • 默认公共边界返回类型

适合:

  • 模块 API
  • 库 API
  • App API

优点:

  • 统一
  • 稳定
  • 对底层错误变化最不敏感

注意:

  • 不建议所有内部实现都直接从它开始

§pi_result::Result<T, C>

pub type Result<T, C> = core::result::Result<T, error_stack::Report<C>>;

作用:

  • 内部 typed report 链

适合:

  • 内部多层都需要 attach / change_context
  • 需要在公开边界之前保留强类型上下文

注意:

  • 这里的 C 是 Report<C> 的上下文类型,不是标准库裸 Result<T, E> 里的 E

§pi_result::TypedResult<T, C>

pub type TypedResult<T, C> = Result<T, C>;

作用:

  • Result<T, C> 的语义别名

适合:

  • 想显式表达“这里已经进入 report 链”

§pi_result::RawResult<T, E>

pub type RawResult<T, E> = core::result::Result<T, E>;

作用:

  • 轻量叶子错误返回

适合:

  • 叶子函数
  • 热路径
  • thiserror + #[from] 局部聚合

注意:

  • 它不能直接承载 attachment 或 report frame

§推荐组合方式

最推荐的默认依赖链是:

RawResult<T, LocalError>
    -> Result<T, LocalContext>
    -> Result<T>

含义:

  1. 最内层先保持轻量局部错误
  2. 内部需要可观测错误栈时再进入 typed report
  3. 对外边界最终统一收敛为公共 Result<T>

也允许两种简化链路:

RawResult<T, LocalError> -> Result<T>
Result<T, LocalContext> -> Result<T>

§选型速查

§场景 1:纯局部解析逻辑

推荐:

  • RawResult<T, LocalError>

原因:

  • 最轻量
  • 最贴近 Rust 原生写法

§场景 2:内部多层服务逻辑,需要不断补充上下文

推荐:

  • Result<T, LocalContext> 或 TypedResult<T, LocalContext>

原因:

  • 更适合多层 attach / change_context

§场景 3:对外公开库 API

推荐:

  • Result<T>

原因:

  • 公共签名稳定
  • 对调用方最友好

§场景 4:高频热路径

推荐:

  • 先 RawResult<T, LocalError>
  • 到边界再转 Result<T, ...>

原因:

  • 避免过早进入 Report

§场景 5:异步服务请求链

推荐:

  • 内部 TypedResult<T, LocalContext>
  • 边界 Result<T>
  • 配合 SpanTrace

原因:

  • 既能保留 typed 上下文,又能保留逻辑 span 链

§如何定义错误类型

这部分专门回答一个高频问题:在 pi_result 体系里,到底应该定义哪些错误类型,以及它们各自负责什么。

先给最实用的结论:

  1. 叶子函数或热路径,优先定义 LocalError。
  2. 内部模块边界,优先定义 typed Context。
  3. 对外稳定边界,优先映射到公共 ErrorKind。
  4. 运行时变量信息,不要塞进错误枚举字段里,优先定义 Attachment。
  5. 只有在确实需要“整条错误链枚举 provider 数据”时,才进入 nightly 的 provide + request_values/request_refs 路线。

§模式 1:纯局部 thiserror 错误

适合:

  • 字符串解析
  • 参数校验
  • 叶子 IO 包装
  • 热路径局部聚合

示例:

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
enum ParsePortError {
    #[error("invalid port integer")]
    Parse(#[from] core::num::ParseIntError),

    #[error("port out of range")]
    OutOfRange,
}

fn parse_port(input: &str) -> pi_result::RawResult<u16, ParsePortError> {
    let value: u16 = input.parse()?;
    if value == 0 {
        return Err(ParsePortError::OutOfRange);
    }
    Ok(value)
}

这种写法的特点是:

  • #[from] 很方便
  • 枚举可以精确匹配
  • 不强迫函数过早进入 Report

什么时候不要继续堆 LocalError:

  • 你已经跨了模块边界
  • 你已经需要 attach / change_context
  • 你希望上层 API 不被底层错误细节污染

§模式 2:内部 typed context

适合:

  • 一个模块内部有多个层级
  • 中间层想保留强类型语义
  • 最终还没到公共边界

示例:

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
enum ConfigContext {
    #[error("failed to load config")]
    Load,

    #[error("failed to validate config")]
    Validate,
}

fn read_config_text(path: &std::path::Path) -> pi_result::RawResult<String, std::io::Error> {
    std::fs::read_to_string(path)
}

fn load_config(path: &std::path::Path) -> pi_result::TypedResult<String, ConfigContext> {
    let text = read_config_text(path)
        .attach(PathAttachment(path.to_path_buf()))
        .attach(Operation("read_config_text"))
        .into_typed(ConfigContext::Load)?;

    if text.trim().is_empty() {
        return Err(pi_result::error_stack::Report::new(ConfigContext::Validate)
            .attach(Operation("validate_config"))
            .attach("config file is empty"));
    }

    Ok(text)
}

这里 ConfigContext 的职责不是保存所有变量,而是表达“当前层如何解释这个错误”:

  • Load
  • Validate

也就是说,Context 更像“当前层的语义解释”,不是“大一统错误总表”。

§模式 3:内部 typed context 收敛到公共 ErrorKind

适合:

  • 内部错误模型想持续演进
  • 对外签名仍要尽量稳定

示例:

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
enum UserRepoContext {
    #[error("failed to query user record")]
    Query,

    #[error("user record is invalid")]
    Decode,
}

fn query_user(id: u64) -> pi_result::TypedResult<String, UserRepoContext> {
    if id == 0 {
        return Err(pi_result::error_stack::Report::new(UserRepoContext::Query)
            .attach(Operation("query_user"))
            .attach(ResourceId(id.to_string())));
    }

    Ok(format!("user:{id}"))
}

fn get_user_profile(id: u64) -> pi_result::Result<String> {
    let profile = query_user(id)
        .attach(Module("user_service"))
        .attach(Stage("load_profile"))
        .into_error(ErrorKind::Dependency)?;

    Ok(profile)
}

这个模式下的稳定边界很清楚:

  • UserRepoContext:内部可演进
  • ErrorKind::Dependency:对外稳定

下层将来把 Query 拆成 QueryPrimary / QueryReplica,只要对外仍然统一映射到 ErrorKind::Dependency,上层 API 就可以基本无感。

§模式 4:如何在 ErrorKind、Context、Attachment 之间分工

这三者最容易混淆,但职责必须拆开:

  • ErrorKind
    • 给外部调用方看的稳定公共分类
    • 例:InvalidInput、Dependency、Internal
  • Context
    • 给当前层看的 typed 解释视角
    • 例:ConfigContext::Validate、RequestContext::Storage
  • Attachment
    • 给观测、诊断、日志、测试断言看的运行时变量
    • 例:Operation("decode_request")、ResourceId(42)、PathAttachment(path)

一个经验法则:

  • “调用方只需要知道大类”放 ErrorKind
  • “这一层到底把它解释成什么失败”放 Context
  • “资源名、阶段名、请求 ID、文件路径、重试次数”放 Attachment

不推荐这样做:

  • 把所有运行时变量都塞进 ErrorKind
  • 把公共稳定分类直接做成内部所有层的唯一枚举
  • 把 Context 既当公共 API 又当日志字段容器

§模式 5:advanced provider 数据暴露

适合:

  • 你想在最终处理者处枚举整条错误链上的“同类型派生数据”
  • 你不想把这些派生值都显式变成 attachment
  • 你接受 nightly 工具链

这个模式通常用于:

  • SQL 状态码
  • 分片号
  • 机器号
  • 诊断建议码
  • 可复制的小值摘要

示例:

#![cfg_attr(nightly, feature(error_generic_member_access))]

use core::{error::Request, fmt};
use pi_result::prelude::*;

#[derive(Debug)]
struct SqlContext {
    shard: u16,
    sql_state: u32,
}

impl fmt::Display for SqlContext {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.write_str("sql execution failed")
    }
}

impl std::error::Error for SqlContext {
    fn provide<'a>(&'a self, request: &mut Request<'a>) {
        request.provide_ref(&self.shard);
        request.provide_value(self.sql_state);
    }
}

let report = pi_result::error_stack::Report::new(SqlContext {
    shard: 7,
    sql_state: 23505,
});

let shards = report.request_refs::<u16>().copied().collect::<Vec<_>>();
let sql_states = report.request_values::<u32>().collect::<Vec<_>>();

assert_eq!(shards, vec![7]);
assert_eq!(sql_states, vec![23505]);

注意:

  • 这是 nightly 增强路线,不是 stable 主路径
  • 如果你只是想记录一个可打印上下文,通常 attach 已经足够
  • 如果你想枚举同类型多份 provider 数据,provide + request_* 才真正有意义

§如何使用、访问和遍历 Report

这部分专门说明最终错误处理者如何读取 Report。

一个核心原则:

  • stable 路径优先使用“当前值、是否存在、最近一层”的检查方式
  • 只有在你确实需要全量枚举时,才进入 frames() 或 nightly request_* 路线

§基础读取:当前公共语义与是否包含某类数据

适合:

  • App 顶层分类处理
  • 日志分流
  • 监控告警分级

示例:

use pi_result::prelude::*;

let report = parse_public_port("0").expect_err("zero port should fail");

assert_eq!(report.current_kind(), &ErrorKind::InvalidInput);
assert_eq!(report.current_context(), &ErrorKind::InvalidInput);
assert!(report.has_kind(ErrorKind::InvalidInput));
assert!(report.contains::<ParsePortError>());

推荐优先级:

  1. 先看 current_kind() / current_context()
  2. 再看 has_kind() / contains_context::<T>()
  3. 最后再去拿 attachment 或 deeper frame

§读取最近一层 context / attachment

适合:

  • 只关心最近一次补充的同类上下文
  • 想在最终处理者处取“最新 request_id / operation / stage”

示例:

use pi_result::prelude::*;

let report = parse_public_port("0").expect_err("zero port should fail");

let latest_operation = report.attachment_ref::<Operation>();
assert_eq!(latest_operation, Some(&Operation("parse_public_port")));

let latest_input = report.downcast_ref::<String>();
assert_eq!(latest_input.map(String::as_str), Some("input=0"));

let local_error = report.downcast_ref::<ParsePortError>();
assert!(matches!(local_error, Some(ParsePortError::OutOfRange)));

这里的区别是:

  • attachment_ref::<T>()
    • 是 pi_result 对“取最近一个 attachment”的薄封装
  • downcast_ref::<T>()
    • 是 error-stack 原生能力
    • 可以取最近一个 context,也可以取最近一个 attachment

§手工遍历整个 frame 栈

适合:

  • 你想做自定义日志导出
  • 你想对每一层 frame 做分类统计
  • 你想在不依赖 nightly 的情况下做“全链路扫描”

示例:

use pi_result::error_stack::{AttachmentKind, FrameKind};
use pi_result::prelude::*;

let report = parse_public_port("0").expect_err("zero port should fail");

for frame in report.frames() {
    match frame.kind() {
        FrameKind::Context(context) => {
            eprintln!("context: {context}");
        }
        FrameKind::Attachment(AttachmentKind::Printable(attachment)) => {
            eprintln!("attachment: {attachment}");
        }
        FrameKind::Attachment(AttachmentKind::Opaque(_)) => {}
        FrameKind::Attachment(_) => {}
    }

    if let Some(operation) = frame.downcast_ref::<Operation>() {
        eprintln!("operation = {}", operation.0);
    }
}

这条路线的特点是:

  • stable 可用
  • 能覆盖整条链
  • 但你需要自己决定如何解释每个 frame

§聚合多个 Report 后读取多个当前 context

适合:

  • 批量校验
  • 批量导入
  • 一次返回多个同类失败

示例:

use pi_result::error_stack::Report;
use pi_result::prelude::*;

fn validate_name(name: &str) -> pi_result::Result<()> {
    if name.trim().is_empty() {
        return Err(Report::new(ErrorKind::InvalidInput)
            .attach(Operation("validate_name"))
            .attach("name is empty"));
    }
    Ok(())
}

fn validate_email(email: &str) -> pi_result::Result<()> {
    if !email.contains('@') {
        return Err(Report::new(ErrorKind::InvalidInput)
            .attach(Operation("validate_email"))
            .attach("email is invalid"));
    }
    Ok(())
}

let mut combined = validate_name("").expect_err("name should fail").expand();
combined.push(validate_email("broken").expect_err("email should fail"));

let public_kinds = combined.current_contexts().copied().collect::<Vec<_>>();
assert_eq!(public_kinds, vec![ErrorKind::InvalidInput, ErrorKind::InvalidInput]);

这类 Report<[C]> 是 advanced 路线。它更适合:

  • 批量结果归并
  • 一次上报多个同类错误

如果你的场景只是“单个错误一直向上冒泡”,通常不需要进入这个模型。

§nightly 下枚举整条错误链上的所有同类型数据

适合:

  • 同一种 attachment 会被多层重复附加
  • 你要拿到“所有匹配项”,而不只是最近一个
  • 你要枚举 provider 数据

示例 1:枚举所有同类型 attachment

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[error("decode failed")]
struct DecodeContext;

let report = pi_result::error_stack::Report::new(DecodeContext)
    .attach(Operation("read"))
    .attach(Operation("decode"))
    .attach(Operation("normalize"));

let operations = report
    .request_refs::<Operation>()
    .map(|operation| operation.0)
    .collect::<Vec<_>>();

assert_eq!(operations, vec!["normalize", "decode", "read"]);

示例 2:同时枚举 attachment 与 provider 值

#![cfg_attr(nightly, feature(error_generic_member_access))]

use core::{error::Request, fmt};
use pi_result::prelude::*;

#[derive(Debug)]
struct StorageContext {
    shard: u16,
    retry_budget: u8,
}

impl fmt::Display for StorageContext {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.write_str("storage access failed")
    }
}

impl std::error::Error for StorageContext {
    fn provide<'a>(&'a self, request: &mut Request<'a>) {
        request.provide_ref(&self.shard);
        request.provide_value(self.retry_budget);
    }
}

let report = pi_result::error_stack::Report::new(StorageContext {
    shard: 3,
    retry_budget: 5,
})
.attach(Operation("read_from_replica"))
.attach(Operation("fallback_primary"));

let operations = report
    .request_refs::<Operation>()
    .map(|operation| operation.0)
    .collect::<Vec<_>>();
let retry_budget = report.request_values::<u8>().collect::<Vec<_>>();

assert_eq!(operations, vec!["fallback_primary", "read_from_replica"]);
assert_eq!(retry_budget, vec![5]);

什么时候选哪一种:

  • 只要当前公共分类:current_kind()
  • 只要知道有没有某种内部语义:contains_context::<T>()
  • 只要最近一个 attachment:attachment_ref::<T>()
  • 想自己扫描整条 frame 栈:frames()
  • 想枚举所有同类型数据:nightly 下 request_refs() / request_values()

§跨库并入与统一冒泡

这部分专门回答一个在真实工程里非常关键的问题:

  • 如果依赖库 B 的对外 API 已经返回 pi_result::Result<T>,上层库 A 能不能继续把它并入自己的错误处理链?
  • 并入之后,能不能继续保留错误的类型化、结构化、可匹配、可跟踪、可观测?
  • 模块内部有多个不同的自定义错误时,能不能统一地继续使用 ? 往最上层的 pi_result::Result<T> 冒泡?

答案是:可以,但要分清“直接继续 ?”和“在 ? 之前显式切换边界”这两种情况。

核心规则:

  1. 如果库 A 和库 B 共享同一种公共 pi_result::Result<T> 语义,并且 A 不需要改公共错误分类,那么 A 可以在补完 attachment 后直接 ?。
  2. 如果库 A 想给来自库 B 的错误增加自己的 typed context,或者要把 B 的公共 ErrorKind 重新解释成 A 的新公共语义,那么先 into_typed(...) / into_error(...),再 ?。
  3. 如果模块内部有多种不同的局部自定义错误,它们不能“裸着直接 ? 到统一公共 Result<T>”;但可以在每个合适边界先 .into_error(...) 或 .into_typed(...),然后统一继续 ?。

§场景 1:库 B 已返回 pi_result::Result<T>,库 A 直接继续 ?

这是最简单的跨库并入模式。

适合:

  • 库 B 已经对外统一收敛成 pi_result::Result<T>
  • 库 A 只想补充自己的 attachment
  • 库 A 不想改当前公共 ErrorKind

示例:

use pi_result::prelude::*;

mod library_b {
    use pi_result::prelude::*;

    pub fn fetch_config() -> pi_result::Result<&'static str> {
        Err(pi_result::error_stack::Report::new(ErrorKind::NotFound)
            .attach(Module("library_b"))
            .attach(Operation("fetch_config")))
    }
}

fn library_a_passthrough() -> pi_result::Result<&'static str> {
    let config = library_b::fetch_config()
        .attach(Module("library_a"))
        .attach(Operation("use_library_b"))?;

    Ok(config)
}

let report = library_a_passthrough().expect_err("dependency should fail");

assert_eq!(report.current_kind(), &ErrorKind::NotFound);
assert!(report.has_kind(ErrorKind::NotFound));
assert!(report.frames().any(|frame| frame.downcast_ref::<Module>() == Some(&Module("library_b"))));
assert!(report.frames().any(|frame| frame.downcast_ref::<Module>() == Some(&Module("library_a"))));

这里发生了什么:

  • 库 B 已经把自己的错误收敛成 Report<ErrorKind>
  • 库 A 因为返回类型同样是 pi_result::Result<T>,所以可以直接 ?
  • ? 不会丢失库 B 原来已经构建好的错误链
  • 库 A 只是在 ? 之前继续补充了自己的 attachment

也就是说,库 B 的公共 Result<T> 可以自然地成为库 A 错误链的一部分。

§场景 2:库 A 把库 B 的 Result<T> 并入自己的 typed/public 错误链

这是更常见、也更强的模式。

适合:

  • 库 B 对外已经返回 pi_result::Result<T>
  • 库 A 想继续保留自己的 typed context
  • 库 A 对外还想重新解释成新的公共 ErrorKind

示例:

use pi_result::prelude::*;

mod library_b {
    use pi_result::prelude::*;

    pub fn fetch_user(id: u64) -> pi_result::Result<String> {
        if id == 0 {
            return Err(pi_result::error_stack::Report::new(ErrorKind::NotFound)
                .attach(Module("library_b"))
                .attach(Operation("fetch_user"))
                .attach(ResourceId(id.to_string())));
        }

        Ok(format!("user:{id}"))
    }
}

#[derive(Debug, ThisError)]
enum LibraryAContext {
    #[error("failed to load dependency user")]
    LoadDependencyUser,
}

fn library_a_internal(id: u64) -> pi_result::TypedResult<String, LibraryAContext> {
    let user = library_b::fetch_user(id)
        .attach(Module("library_a"))
        .attach(Operation("call_library_b::fetch_user"))
        .into_typed(LibraryAContext::LoadDependencyUser)?;

    Ok(user)
}

fn library_a_public(id: u64) -> pi_result::Result<String> {
    let user = library_a_internal(id)
        .attach(Stage("public_api"))
        .into_error(ErrorKind::Dependency)?;

    Ok(user)
}

let report = library_a_public(0).expect_err("dependency should fail");

assert_eq!(report.current_kind(), &ErrorKind::Dependency);
assert!(report.has_kind(ErrorKind::NotFound));
assert!(report.contains_context::<LibraryAContext>());
assert!(report.frames().any(|frame| frame.downcast_ref::<Module>() == Some(&Module("library_b"))));
assert!(report.frames().any(|frame| frame.downcast_ref::<Module>() == Some(&Module("library_a"))));

这个模式下,错误链上会同时保留:

  • 库 B 原来的公共 ErrorKind
  • 库 A 新增的 typed context
  • 库 A 对外重新定义后的公共 ErrorKind
  • 库 A 和库 B 各自补充的 attachment

所以答案是明确的:库 B 的 pi_result::Result<T> 完全可以在保留类型化、结构化、可匹配、可观测能力的前提下,并入库 A 自己的错误构建/处理/上报链。

更进一步地说:

  • current_kind() 反映的是“当前最外层公共解释”
  • has_kind(...) 可以帮助你看到链中是否还保留库 B 之前的公共语义
  • contains_context::<AContext>() 可以帮助你看到库 A 的 typed 内部解释
  • frames() / attachment_ref() / nightly request_*() 则让你继续读取完整上下文链

§场景 3:模块内部不同自定义错误统一收敛后继续 ?

这个问题也很关键。答案同样是:可以,但方式不是“裸 ?”,而是“先收敛,再 ?”。

适合:

  • 模块内部有多个叶子自定义错误
  • 最终模块公开签名仍然想统一为 pi_result::Result<T>

示例:

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[error("invalid header")]
struct HeaderError;

#[derive(Debug, ThisError)]
#[error("invalid payload")]
struct PayloadError;

fn parse_header(input: &[u8]) -> pi_result::RawResult<&[u8], HeaderError> {
    if input.is_empty() {
        return Err(HeaderError);
    }

    Ok(input)
}

fn parse_payload(input: &[u8]) -> pi_result::RawResult<usize, PayloadError> {
    if input == b"bad" {
        return Err(PayloadError);
    }

    Ok(input.len())
}

fn handle(input: &[u8]) -> pi_result::Result<usize> {
    let header = parse_header(input)
        .attach(Operation("parse_header"))
        .into_error(ErrorKind::InvalidInput)?;

    let payload_len = parse_payload(header)
        .attach(Operation("parse_payload"))
        .into_error(ErrorKind::InvalidInput)?;

    Ok(payload_len)
}

let header_report = handle(&[]).expect_err("header should fail");
assert!(header_report.contains::<HeaderError>());

let payload_report = handle(b"bad").expect_err("payload should fail");
assert!(payload_report.contains::<PayloadError>());

这里有一个非常重要的语义点:

  • HeaderError 和 PayloadError 这两种不同的局部错误,不能直接“裸着” ? 到 pi_result::Result<T>
  • 但它们可以先在调用点被显式转换成统一公共边界:
    • .into_error(ErrorKind::InvalidInput)?
  • 一旦转换完成,后面就可以统一继续 ?

如果模块内部还想保留更强的 typed 语义,也可以这样写:

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
#[error("invalid header")]
struct HeaderError;

#[derive(Debug, ThisError)]
#[error("invalid payload")]
struct PayloadError;

#[derive(Debug, ThisError)]
enum DecodeContext {
    #[error("failed to parse header")]
    Header,

    #[error("failed to parse payload")]
    Payload,
}

fn parse_header(input: &[u8]) -> pi_result::RawResult<&[u8], HeaderError> {
    if input.is_empty() {
        return Err(HeaderError);
    }

    Ok(input)
}

fn parse_payload(input: &[u8]) -> pi_result::RawResult<usize, PayloadError> {
    if input == b"bad" {
        return Err(PayloadError);
    }

    Ok(input.len())
}

fn decode_internal(input: &[u8]) -> pi_result::TypedResult<usize, DecodeContext> {
    let header = parse_header(input)
        .attach(Operation("parse_header"))
        .into_typed(DecodeContext::Header)?;

    let payload = parse_payload(header)
        .attach(Operation("parse_payload"))
        .into_typed(DecodeContext::Payload)?;

    Ok(payload)
}

fn decode_public(input: &[u8]) -> pi_result::Result<usize> {
    let payload = decode_internal(input)
        .attach(Module("decoder"))
        .into_error(ErrorKind::InvalidInput)?;

    Ok(payload)
}

这个模式下:

  • 内部不同局部错误仍然各自独立、可匹配
  • 内部继续通过 typed context 统一表达解释语义
  • 最上层仍然稳定收敛为统一 pi_result::Result<T>
  • 每一步都可以自然继续使用 ?

一句话总结这部分:

  • “库 B 的 pi_result::Result<T> 并入库 A 错误链”是天然支持的
  • “模块内部多个不同自定义错误统一往最上层 pi_result::Result<T> 冒泡”也是支持的
  • 关键不是依赖隐式魔法,而是在边界点显式使用:
    • attach
    • attach_with
    • into_typed
    • into_error 然后继续 ?

§标准库与第三方错误互操作

这一节专门解决“现有库已经用了别的 Result/Error 风格,怎么可靠并入 pi_result”的问题。

当前 pi_result 的互操作主线是:

  1. 尽量保留原始错误类型,不强行抹平
  2. 在公共边界标准化为稳定 ErrorKind
  3. 用 typed context 表达本层解释
  4. 用 attachment 补来源、依赖、资源、路径、阶段等可观察信息

为此,V1 现在提供了专门的 interop 能力:

  • InteropResultExt::into_error_by(...)
  • InteropResultExt::into_typed_by(...)
  • InteropResultExt::into_classified_error()
  • InteropResultExt::into_report_with_source()
  • ClassifyErrorKind
  • classify_io_error(...)
  • source_type_name_of::<E>()

同时,公共错误分类里新增了两个常用兜底项:

  • ErrorKind::Io
    • 用于“通用 IO 失败,但当前层不再继续细分”
  • ErrorKind::Other
    • 用于“当前确实无法稳定归类的最后兜底类型”

§场景 1:std::io::Result<T> 自动标准化

这是改造现有代码时最常见的一类。

适合:

  • 文件读写
  • socket / pipe / fd 访问
  • 任何直接返回 std::io::Result<T> 的老代码

示例:

use pi_result::prelude::*;

fn read_text(path: &std::path::Path) -> pi_result::Result<String> {
    std::fs::read_to_string(path)
        .into_report_with_source()
        .attach(DependencyName("std::fs"))
        .attach(PathAttachment(path.to_path_buf()))
        .into_classified_error()
}

这里会发生 3 件事:

  1. 原始 std::io::Error 会被保留在 Report 里
  2. 来源类型会被附加为 SourceTypeName::of::<std::io::Error>()
  3. std::io::ErrorKind 会被标准化到公共 ErrorKind

默认映射策略是保守的:

  • NotFound -> ErrorKind::NotFound
  • PermissionDenied -> ErrorKind::PermissionDenied
  • AlreadyExists -> ErrorKind::AlreadyExists
  • TimedOut -> ErrorKind::Timeout
  • InvalidInput -> ErrorKind::InvalidInput
  • InvalidData -> ErrorKind::Corrupted
  • WouldBlock -> ErrorKind::Busy
  • Interrupted -> ErrorKind::Cancelled
  • 其它 -> ErrorKind::Io

§场景 2:第三方 thiserror 错误并入 pi_result

适合:

  • 依赖库返回自定义枚举错误
  • 你希望保留原始错误类型并做稳定公共分类

示例:

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
enum HttpClientError {
    #[error("invalid url")]
    InvalidUrl,

    #[error("transport failure")]
    Transport,
}

impl ClassifyErrorKind for HttpClientError {
    fn classify_error_kind(&self) -> ErrorKind {
        match self {
            Self::InvalidUrl => ErrorKind::InvalidInput,
            Self::Transport => ErrorKind::Dependency,
        }
    }
}

fn third_party_http_call(url: &str) -> pi_result::RawResult<&'static str, HttpClientError> {
    if !url.starts_with("https://") {
        return Err(HttpClientError::InvalidUrl);
    }

    Err(HttpClientError::Transport)
}

fn use_third_party_http(url: &str) -> pi_result::Result<&'static str> {
    third_party_http_call(url)
        .into_report_with_source()
        .attach(DependencyName("example_http"))
        .attach(Module("api_client"))
        .attach(Operation("third_party_http_call"))
        .into_classified_error()
}

如果你不想给错误类型实现 ClassifyErrorKind,也可以直接用 closure:

use pi_result::prelude::*;


fn use_third_party_http(url: &str) -> pi_result::Result<&'static str> {
    third_party_http_call(url)
        .attach(DependencyName("example_http"))
        .into_error_by(|error| match error.current_context() {
            HttpClientError::InvalidUrl => ErrorKind::InvalidInput,
            HttpClientError::Transport => ErrorKind::Dependency,
        })
}

注意:

  • 如果你在 into_error_by(...) 之前已经调用了 attach(...) / attach_with(...)
  • 那么闭包里看到的错误值通常已经是 Report<LocalError>,而不是裸 LocalError
  • 这时可以通过 error.current_context() 继续读取原始当前 context

§场景 3:第三方 error_stack::Report<C> 继续被重新分类

适合:

  • 依赖库已经在用 error-stack
  • 它没有使用 pi_result
  • 但你仍然想把它继续并入自己的公共 Result<T>

示例:

use pi_result::prelude::*;

#[derive(Debug, ThisError)]
enum RemoteContext {
    #[error("peer unavailable")]
    Unavailable,

    #[error("peer rejected request")]
    Rejected,
}

impl ClassifyErrorKind for RemoteContext {
    fn classify_error_kind(&self) -> ErrorKind {
        match self {
            Self::Unavailable => ErrorKind::Dependency,
            Self::Rejected => ErrorKind::Other,
        }
    }
}

fn remote_dependency_call(
    kind: RemoteContext,
) -> core::result::Result<(), pi_result::error_stack::Report<RemoteContext>> {
    Err(pi_result::error_stack::Report::new(kind)
        .attach(DependencyName("remote_peer"))
        .attach(Operation("remote_dependency_call")))
}

fn app_remote_boundary(kind: RemoteContext) -> pi_result::Result<()> {
    remote_dependency_call(kind)
        .attach(Module("app"))
        .into_classified_error()
}

这条链路的关键点是:

  • 原始 RemoteContext 不会丢
  • 第三方原有 attachment 不会丢
  • 上层仍可得到统一公共 ErrorKind

§场景 4:原始错误来源、依赖名与可观察性

当你在融合标准库/第三方错误时,推荐优先补这几类信息:

  • DependencyName
    • 错误来自哪个依赖或子系统
  • SourceTypeName
    • 原始错误类型是什么
  • Operation
    • 当前在做什么
  • Module
    • 当前位于哪个模块
  • PathAttachment / ResourceId / ResourceName
    • 具体资源是谁

常见组合写法:

use pi_result::prelude::*;

fn call_dependency() -> pi_result::Result<()> {
    Err::<(), std::io::Error>(std::io::Error::from(std::io::ErrorKind::TimedOut))
        .into_report_with_source()
        .attach(DependencyName("object_store"))
        .attach(Module("asset_loader"))
        .attach(Operation("download_blob"))
        .into_classified_error()?;

    Ok(())
}

§场景 5:不完全匹配 pi_result 约束的错误如何处理

pi_result 当前最顺手支持的是:

  • E: std::error::Error + Send + Sync + 'static
  • 或已经是 error_stack::Report<C>

如果第三方错误不满足这些约束,例如:

  • 不是 std::error::Error
  • 不是 Send + Sync
  • 生命周期不满足 'static

此时不要强行把原始错误对象塞进 Report。更合理的做法是:

  1. 把原始错误快照成一个稳定的结构化 ExternalError
  2. 自动补上 SourceTypeName
  3. 再收敛到 typed/public 错误链

pi_result 现在提供了两条路径。

第一条路径:原始错误至少有 Display + Debug

use std::{fmt, rc::Rc};

use pi_result::prelude::*;

#[derive(Debug)]
struct BorrowedLegacyError<'a> {
    input: &'a str,
    shared: Rc<String>,
}

impl fmt::Display for BorrowedLegacyError<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "legacy parser rejected `{}` from {}", self.input, self.shared)
    }
}

fn legacy_parse(input: &str) -> core::result::Result<(), BorrowedLegacyError<'_>> {
    Err(BorrowedLegacyError {
        input,
        shared: Rc::new(String::from("legacy_parser")),
    })
}

fn load_from_legacy(input: &str) -> pi_result::Result<()> {
    legacy_parse(input)
        .into_external_error_by(|error| {
            if error.input.contains(' ') {
                ErrorKind::InvalidInput
            } else {
                ErrorKind::Other
            }
        })
        .attach(DependencyName("legacy_parser"))
        .attach(Module("legacy_adapter"))
        .attach(Operation("legacy_parse"))?;

    Ok(())
}

这条路径的特点是:

  • 原始错误可以不是 std::error::Error
  • 可以不是 Send + Sync
  • 可以带借用生命周期
  • 最终错误链里会保留:
    • ExternalError
    • SourceTypeName
    • 你补的业务 attachment

第二条路径:原始错误甚至没有 Display,需要你自己提取稳定信息

use pi_result::prelude::*;

#[derive(Debug)]
struct RawForeignCode {
    code: u16,
    subsystem: &'static str,
}

fn call_raw_ffi() -> pi_result::Result<()> {
    Err::<(), RawForeignCode>(RawForeignCode {
        code: 503,
        subsystem: "ffi_gateway",
    })
    .into_external_error_with(|error| {
        (
            ErrorKind::Dependency,
            ExternalError::new(
                format!("ffi gateway rejected request with code {}", error.code),
                format!("{error:?}"),
            ),
        )
    })
    .attach(DependencyName("ffi_gateway"))
    .attach(Module("ffi_adapter"))
    .attach(Operation("call_raw_ffi"))?;

    Ok(())
}

这条路径适合:

  • FFI 错误
  • C API 错误码
  • 遗留库暴露的裸结构体
  • 你只能拿到字段,拿不到标准 Error trait 的情况

需要注意:

  • into_external_* 系列的目标是“标准化并保留稳定快照”,不是保留原始错误对象本身
  • 进入这条路径后,最终处理者通常应读取:
    • ExternalError
    • SourceTypeName
    • DependencyName
    • Operation / Module
  • 如果原始错误本身已经满足 Error + Send + Sync + 'static,仍应优先用 into_report_with_source()、into_error_by()、into_typed_by() 这些原生并入路径

也就是说,pi_result 的互操作目标是“尽量保留原始类型并标准化边界”;只有在原始错误对象本身无法安全并入 Report 时,才退回到 ExternalError 快照路径。

§panic-free 开发模式

§为什么 pi_result 支持这类开发

如果你的目标是:

  • 不手工 panic!
  • 所有可预料问题都走 Result/Error
  • 每层都能继续补充上下文并上报

那么 pi_result 是支持这种开发模式的。

它的基础工具包括:

  • Result<T> / TypedResult<T, C> / RawResult<T, E>
  • attach / attach_with
  • into_typed / into_error
  • pi_result::ensure!
  • pi_result::bail!

§推荐写法:Result、ensure!、bail!

示例:

use pi_result::prelude::*;

fn validate_port_without_panic(port: i32) -> pi_result::Result<u16> {
    pi_result::ensure!(port >= 0, ErrorKind::InvalidInput);
    pi_result::ensure!(port <= u16::MAX as i32, ErrorKind::InvalidInput);

    if port == 13 {
        pi_result::bail!(ErrorKind::Unsupported);
    }

    Ok(port as u16)
}

这个模式的意图很清楚:

  • 前置条件失败不用 panic!
  • 业务上可预料的拒绝也不用 panic!
  • 统一返回 Result/Error

§边界与限制

这里必须把边界说清楚:

  • pi_result 支持“可预料问题不用手工 panic”的开发模式
  • 但不承诺“整个进程绝对不会 panic”

仍然可能 panic 的场景包括:

  • 真正的程序 bug
  • 不变量被破坏
  • 你自己写的 unwrap() / expect()
  • 第三方库内部 panic

所以更准确的说法是:

  • pi_result 支持模块/库/App 采用 panic-free 的业务错误处理风格
  • 但不会把 panic 语义本身从 Rust 生态里抹掉

如果后续要把 catch_unwind 风格的 panic 边界辅助也纳入 pi_result,需要单独设计,因为那会影响:

  • 语义边界
  • async 行为
  • 性能
  • 稳定性

§从简单到高级的完整示例

以下示例按当前 V1 目标 API 编写。它们是“整条逻辑链如何组织”的 end-to-end 示例;如果你只想先学会如何定义错误类型或如何读取 Report,请先看前面的两节。

§示例 1:最简单的局部错误

适用场景:

  • 纯解析函数
  • 暂时不需要 report 链
use pi_result::prelude::*;

#[derive(Debug, ThisError)]
enum ParsePortError {
    #[error("invalid port integer")]
    Parse(#[from] core::num::ParseIntError),

    #[error("port out of range")]
    OutOfRange,
}

fn parse_port(input: &str) -> pi_result::RawResult<u16, ParsePortError> {
    let value: u16 = input.parse()?;
    if value == 0 {
        return Err(ParsePortError::OutOfRange);
    }
    Ok(value)
}

assert_eq!(parse_port("8080").expect("valid port"), 8080);
assert!(matches!(parse_port("0"), Err(ParsePortError::OutOfRange)));

说明:

  • 这是最简单、最轻量的写法
  • 如果当前层不需要 attachment、change_context,就不必强行进入 Report

§示例 2:在公共边界收敛为统一 Result<T>

适用场景:

  • 模块 API
  • 对外稳定边界
use pi_result::prelude::*;


fn parse_public_port(input: &str) -> pi_result::Result<u16> {
    let value = parse_port(input)
        .attach(Operation("parse_public_port"))
        .attach_with(|| format!("input={input}"))
        .into_error(ErrorKind::InvalidInput)?;

    Ok(value)
}

assert_eq!(parse_public_port("8080").expect("public parse should succeed"), 8080);

let report = parse_public_port("0").expect_err("zero port should map to public error");
assert_eq!(report.current_kind(), &ErrorKind::InvalidInput);
assert_eq!(
    report.attachment_ref::<Operation>(),
    Some(&Operation("parse_public_port")),
);
assert!(debug_message(&report).contains("input=0"));

说明:

  • 下层 ParsePortError 没有泄露到公开签名
  • 当前层给错误补了调用者视角上下文
  • 上层最终只看到 Result<u16>

§示例 3:内部多层 typed report

适用场景:

  • 内部多个层级都要补充上下文
  • 还没到公共边界
use pi_result::prelude::*;

#[derive(Debug, ThisError)]
enum ConfigContext {
    #[error("failed to load config")]
    Load,

    #[error("failed to validate config")]
    Validate,
}

fn read_config_text(path: &std::path::Path) -> pi_result::RawResult<String, std::io::Error> {
    std::fs::read_to_string(path)
}

fn load_config(path: &std::path::Path) -> pi_result::TypedResult<String, ConfigContext> {
    let text = read_config_text(path)
        .attach(PathAttachment(path.to_path_buf()))
        .attach(Operation("read_config_text"))
        .into_typed(ConfigContext::Load)?;

    if text.trim().is_empty() {
        return Err(pi_result::error_stack::Report::new(ConfigContext::Validate)
            .attach(Operation("validate_config"))
            .attach("config file is empty"));
    }

    Ok(text)
}

说明:

  • 这里公开的是内部 typed context ConfigContext
  • 中间层可以继续补充 attachment
  • 还未到最终公共边界

§示例 4:从内部 typed report 收敛到公共边界

适用场景:

  • 库内部逻辑较复杂
  • 对外仍希望统一签名
use pi_result::prelude::*;

fn startup(path: &std::path::Path) -> pi_result::Result<()> {
    let _config = load_config(path)
        .attach(Stage("startup"))
        .attach(Module("app"))
        .into_error(ErrorKind::Internal)?;

    Ok(())
}

说明:

  • 对外只暴露 Result<()>
  • 内部仍然保留 ConfigContext
  • 最终处理者还能继续检查内部 typed frame 和 attachment

§示例 5:最终错误处理

适用场景:

  • App 边界
  • 日志与恢复
use pi_result::prelude::*;

fn run(path: &std::path::Path) {
    match startup(path) {
        Ok(()) => {}
        Err(report) => {
            match report.current_kind() {
                ErrorKind::InvalidInput => {
                    eprintln!("user error: {}", user_message(&report));
                }
                ErrorKind::Internal | ErrorKind::Dependency => {
                    eprintln!("internal error:\n{}", verbose_message(&report));
                    eprintln!("{report:?}");
                }
                _ => {
                    eprintln!("{report}");
                }
            }

            if report.contains_context::<ConfigContext>() {
                eprintln!("config context detected");
            }

            if let Some(path) = report.attachment_ref::<PathAttachment>() {
                eprintln!("config path: {}", path.0.display());
            }
        }
    }
}

说明:

  • 先按公共 ErrorKind 分类
  • 再按内部 typed context 做深一层诊断
  • 再尝试读取 attachment

§示例 6:异步服务场景

适用场景:

  • async 服务
  • 请求链或作业链
use pi_result::prelude::*;

#[derive(Debug, ThisError)]
enum RequestContext {
    #[error("failed to decode request")]
    Decode,

    #[error("failed to access storage")]
    Storage,
}

async fn decode_request(body: &[u8]) -> pi_result::RawResult<String, core::str::Utf8Error> {
    let text = core::str::from_utf8(body)?;
    Ok(text.to_owned())
}

async fn handle_request(body: &[u8], request_id: &str) -> pi_result::Result<String> {
    let text = decode_request(body)
        .await
        .attach(Operation("decode_request"))
        .attach_with(|| format!("request_id={request_id}"))
        .into_typed(RequestContext::Decode)
        .into_error(ErrorKind::InvalidInput)?
        .trim()
        .to_owned();

    if text == "fail" {
        return Err(pi_result::error_stack::Report::new(RequestContext::Storage)
            .attach(Operation("storage_lookup"))
            .attach(format!("request_id={request_id}"))
            .change_context(ErrorKind::Dependency));
    }

    Ok(text)
}

说明:

  • Report 可以在 async 链路中正常传播
  • 如果要更好追踪 async 请求逻辑,建议再启用 SpanTrace

§Backtrace、SpanTrace 和业务上下文链

三者不是一回事。

§Backtrace

作用:

  • 看原生代码调用栈

适合:

  • IO、解析、系统调用、底层崩点排查

优点:

  • 不依赖 tracing

限制:

  • 不够业务语义化

§SpanTrace

作用:

  • 看 tracing span 的逻辑链

适合:

  • async 服务
  • 请求链
  • 作业链

优点:

  • 对业务逻辑链更直观

限制:

  • 依赖 tracing 埋点和 ErrorLayer

§业务上下文链

作用:

  • 通过 change_context 和 attach 明确记录每一层“如何解释这个错误”

适合:

  • 所有需要长期维护和稳定诊断的工程

结论:

  • Backtrace 解决“代码怎么走到这里”
  • SpanTrace 解决“逻辑链路处于什么 span/请求上下文”
  • 业务上下文链解决“当前层如何解释这个错误”

它们可以组合使用,而且推荐组合使用。

§线程安全、异步安全、打印与 Clone

§是否跨线程安全

是。

根据 error-stack 文档,Report<C> 具备 Send 和 Sync 自动 trait,并且:

  • Context 需要满足 Display + Debug + Send + Sync + 'static
  • attachment 也要求 Send + Sync + 'static

因此 pi_result::Error = Report<ErrorKind> 可以跨线程传递和共享。

§是否异步安全

是。

Report<C> 可以在 async 函数中返回、传播并跨 .await 使用。对于多线程执行器,只要你的 future 本身满足 Send,Report<C> 不会成为障碍。

但要注意:

  • “异步安全”不等于“自动有异步调用链追踪”
  • 如果你要看到 async 请求的逻辑 span 链,需要额外启用 SpanTrace

§是否可跟踪

是,但分层次:

  1. 默认就有 context 链和 attachment 链
  2. 若启用并成功捕获 Backtrace,还能看到原生调用栈
  3. 若启用 SpanTrace 并配置 ErrorLayer,还能看到逻辑 span 链

§是否可直接打印

是。

Report 实现了:

  • Display
  • Debug

常见打印方式:

use pi_result::prelude::*;

let report = Err::<(), std::io::Error>(std::io::Error::from(std::io::ErrorKind::NotFound))
    .attach(Operation("print_demo"))
    .into_error(ErrorKind::NotFound)
    .expect_err("expected public report");

assert_eq!(format!("{report}"), "not found");
assert!(format!("{report:#}").contains("not found"));
assert!(format!("{report:?}").contains("print_demo"));

推荐理解为:

  • {}:当前 context
  • {:#}:全部 context
  • {:?}:完整调试输出,包含 attachment 和额外调试信息

§是否可直接 Clone

默认不可以。

error_stack::Report<C> 没有实现 Clone,因此:

  • pi_result::Error 默认不可 Clone
  • pi_result::Result<T> 也通常不可 Clone

这是合理的,因为错误报告里可能包含:

  • 多层 frame
  • attachment
  • Backtrace
  • SpanTrace

如果业务确实需要“可复制的错误摘要”,更推荐:

  1. 提取成自己的可 Clone 诊断结构
  2. 或提取公共 ErrorKind
  3. 或提取关心的 attachment 和格式化文本

§默认 feature 与建议配置

§Backtrace

error-stack 的 backtrace feature 默认开启,但是否真正输出 backtrace 还取决于环境变量,例如:

RUST_BACKTRACE=1

或:

RUST_LIB_BACKTRACE=1

§SpanTrace

spantrace 默认不是自动可用的。要使用它,通常需要:

  1. 启用 error-stack 的 spantrace feature
  2. 配置 tracing-error::ErrorLayer
  3. 在应用中合理布置 tracing span

当前 crate 提供可选 feature:

[features]
spantrace = ["error-stack/spantrace", "dep:tracing", "dep:tracing-error", "dep:tracing-subscriber"]

验证 SpanTrace 链路时可使用:

cargo test --features spantrace

§基准测试

当前仓库已经提供基准文件:

  • benches/propagation.rs

覆盖场景:

  1. 成功路径别名开销
  2. 失败路径 attach_with 开销
  3. 边界转换开销
  4. 多层上下文叠加开销
  5. 12 层深链路叠加开销
  6. 32 / 64 / 128 层极深链路叠加开销
  7. 严格最坏模型下的 32 / 64 / 128 层链路开销
  8. 12 层、极深链路和严格最坏模型 + Backtrace
  9. 12 层、极深链路和严格最坏模型 + SpanTrace
  10. 12 层、极深链路和严格最坏模型 + Backtrace + SpanTrace
  11. 高频错误突发下的 64 / 256 / 1024 次深链路上报
  12. 叶子错误的 Backtrace / SpanTrace 捕获开销
  13. 控制变量 benchmark:
    • 纯 change_context 深度成本
    • 静态 attach 数量成本
    • 动态 attach_with 数量成本

建议命令:

cargo bench --bench propagation

启用 SpanTrace benchmark:

cargo bench --bench propagation --features spantrace

注意:

  • benchmark 结果与机器性能、编译器、运行时负载直接相关
  • 当前 benchmark 主要用于相对比较,不应把一次运行结果当作绝对指标
  • Linux 生产环境结果才是性能与行为基线,Windows 结果只用于开发期参考
  • 评估 trace 成本时,应重点对比:
    • deep_multi_module_context_stacking_12_layers
    • deep_multi_module_context_stacking_12_layers_with_backtrace
    • deep_multi_module_context_stacking_12_layers_with_spantrace
    • deep_multi_module_context_stacking_12_layers_with_backtrace_and_spantrace
    • extreme_depth_matrix_*
    • worst_case_depth_matrix_*
    • controlled_change_context_depth_*
    • controlled_static_attachment_count_*
    • controlled_attach_with_count_*
    • worst_case_burst_depth_64_*
    • extreme_burst_depth_128_*
    • burst_64_*

§性能边界速查

以下结论是基于当前测试模型和已有多轮 benchmark 的稳定趋势,不是跨机器的绝对承诺:

场景典型量级主要成本来源
成功路径皮秒级几乎可忽略
12 层中深度单次错误几微秒report 构建 + frame 叠加
12 层中深度单次错误 + SpanTrace更高的几微秒SpanTrace 是主要增量
128 层极深链路单次错误数十微秒深链路 frame 与 attachment 本身主导
严格最坏模型单次错误更高的数十微秒到百微秒级每层 attachment + change_context 全开
控制变量对照组取决于输入规模可拆分观察 change_context、静态 attach、动态 attach_with 的增量
128 层极深链路 1024 次 burst数十毫秒错误链规模与上报频率主导

工程上可据此先做两条判断:

  • 中等深度但错误频繁的场景,应谨慎默认开启 SpanTrace
  • 极深链路场景,应优先控制 change_context / attach 次数、attachment 数量和错误突发频率

§Linux 成本归因速查

以下是当前 Linux 本地缩样本 benchmark 的代表性对照,用来拆分:

  • change_context 深度成本
  • 静态 attach 数量成本
  • 动态 attach_with 数量成本
  • Backtrace / SpanTrace / 全开 的固定底座与增量

这些数字仍然只用于相对比较,但已经足以支持工程判断。

控制变量无 trace仅 Backtrace仅 SpanTraceBacktrace + SpanTrace
change_context depth=128约 7.45 us约 11.83 us约 10.07 us约 30.94 us
静态 attach count=16约 0.69 us约 4.26 us约 3.07 us约 8.88 us
动态 attach_with count=16约 1.01 us约 4.85 us约 2.41 us约 8.92 us

可先按下面的方式理解:

  • 无 trace 时,真正随规模明显增长的是 frame 深度;change_context 的线性增长比 attachment 数量更显著。
  • 无 trace 时,attach_with 确实比静态 attach 更贵,但两者仍处于同一数量级,尚未成为压倒性瓶颈。
  • 只开 Backtrace 或只开 SpanTrace 时,小规模 attachment 链路就会先出现一个微秒级固定成本底座;这部分成本通常比单个 attachment 本身更大。
  • Backtrace + SpanTrace 全开时,固定底座会进一步抬高;一旦链路层数继续增长,change_context 深度增长重新成为主要放大器。
  • 因此,在真实系统里如果要先做收敛,优先级通常是:
    1. 控制错误链层数
    2. 减少动态字符串 attach_with
    3. 只在真正需要的链路上开启 SpanTrace

补充说明:

  • SpanTrace 单独样本在小规模输入下波动比 Backtrace 更大,因此更适合看趋势而不是执着于单次绝对值。
  • 当前控制变量 benchmark 已切换为更稳定的参数:
    • warm_up_time = 1s
    • measurement_time = 3s
    • sample_size = 20
    • SamplingMode::Flat
  • 在这组新参数下,代表性 Linux 样本可参考:
    • controlled_change_context_depth_with_backtrace_and_spantrace/depth/128: 约 50.11 us
    • controlled_attach_with_count_with_backtrace_and_spantrace/count/16: 约 8.53 us
    • controlled_static_attachment_count_with_spantrace/count/16: 约 1.96 us
  • 即使单个 SpanTrace 样本仍会有一定抖动,新的采样配置已经更适合做“趋势判断”和“成本级别判断”。

§稳定版与 nightly 的差异

§stable 默认路径

当前设计中,稳定版优先围绕这些能力:

  • current_context()
  • contains::<T>()
  • downcast_ref::<T>()
  • ErrorInspectExt::{current_kind, has_kind, contains_context, attachment_ref}

§nightly 增强路径

当前已实现的 nightly 增强能力为:

  • 工具链要求:nightly Rust
  • 无需额外启用 nightly Cargo feature
  • trait:
    • NightlyErrorInspectExt::request_refs::<T>()
    • NightlyErrorInspectExt::request_values::<T>()
  • 通用辅助函数:
    • request_refs::<C, T>(&Report<C>)
    • request_values::<C, T>(&Report<C>)
  • 预导入:
    • RequestRef
    • RequestValue

它们的价值在于:

  • 枚举整个错误链上所有匹配类型的数据
  • 而不只是取最近一个

验证命令:

cargo +stable test
cargo +stable test --features spantrace
cargo +nightly test
cargo +nightly test --features spantrace

适用场景:

  • 一条错误链上存在多层同类型 attachment
  • 需要枚举全部 Operation / Suggestion / RetryCount
  • Context 通过 Error::provide 暴露了额外 provider 数据
  • 需要同时抓取 provider 数据和 attachment,而不仅是最近一个匹配项

§为什么统一暴露 thiserror 和 error-stack

因为这两个库本身就是 pi_result 的核心基础:

  • thiserror 负责结构化错误定义
  • error-stack 负责错误传播、上下文堆叠与观测

统一暴露它们有几个好处:

  1. 下游用户少写依赖与导入样板
  2. 项目内部风格更统一
  3. 后续 feature 透传更集中

§当前文档状态

本文档当前仍会继续随实现迭代维护,但现在已经区分了 3 类示例:

  • 入门级、可独立运行的示例直接作为 doctest 执行
  • 复杂传播、异步与 trace 示例继续由集成测试验证
  • 纯说明性片段保持为普通代码块,不再伪装成低价值 doctest

当前还额外保证:

  • 标准库与第三方错误互操作
  • panic-free 开发模式
  • 如何使用、访问和遍历 Report
  • 如何定义错误类型

这些章节中的关键示例(examples)纳入文档测试、单元测试或集成测试映射(doctest/unit-test/integration-test mapping)。 本轮 Linux 默认回归(default regression)使用 rustc 1.99.0-nightly (eff8269f7 2026-07-18), 命令为 cargo test --offline --locked -j1 -- --test-threads=1 --nocapture, 文档测试(doctests)为 39 passed; 0 failed; 0 ignored。 “快速开始与兼容派生(Quick Start and Compatible Derive)”中的重命名、间接重导出与夜间提供者 (renaming/indirect re-export/nightly provider)另由真实独立下游工程(independent downstream projects)验证; 这些工程(projects)不额外依赖 thiserror 或 pi_result_macros。 上述实际结果(actual results)不等于真实稳定版工具链(stable toolchain)也已验证, 也不表示所有未来依赖版本或任意用户输入(future dependency versions/arbitrary user inputs)均已穷尽测试(exhaustively tested)。 pi_result 的实现会按模块依赖从底向上逐步扩展。 当前阶段已落地基础类型层与边界传播层的前半部分: kind、result、attachment、boundary,以及观测/格式化/测试辅助与 prelude。

Re-exports§

pub use crate::boundary::IntoErrorExt;
pub use crate::boundary::IntoTypedContextExt;
pub use crate::fmt::debug_message;
pub use crate::fmt::user_message;
pub use crate::fmt::verbose_message;
pub use crate::inspect::ErrorInspectExt;
pub use crate::interop::ClassifyErrorKind;
pub use crate::interop::ExternalError;
pub use crate::interop::InteropResultExt;
pub use crate::interop::classify_io_error;
pub use crate::interop::source_type_name_of;
pub use crate::kind::ErrorKind;
pub use crate::result::Error;
pub use crate::result::ErrorReport;
pub use crate::result::RawResult;
pub use crate::result::Result;
pub use crate::result::TypedResult;
pub use error_stack;
pub use crate::prelude::*;

Modules§

attachment
标准结构化 attachment 定义。
boundary
边界转换辅助 trait。
fmt
统一错误输出格式辅助。
inspect
稳定版错误检查辅助。
interop
标准库 / 第三方错误互操作辅助。
kind
公共稳定错误语义定义。
prelude
pi_result 预导入模块。
result
pi_result 的基础结果与错误类型别名。
testing
测试断言辅助。
thiserror
兼容重导出入口(compatible re-export entry);普通使用推荐预导入(prelude)。 Error 派生(derive)来自配套宏库(companion macro crate),其它名字(names)沿上游导出(exports)。

Macros§

bail
Creates a Report and returns it as Result.
ensure
Ensures $cond is met, otherwise return an error.