Orion Error Engineering
Use this skill for source-accurate work with the orion-error Rust crate.
First Checks
- Locate the crate root. In this workspace it is usually
orion-error/. - Treat
src/,tests/, and compiling examples as source of truth. - For
0.9.x, preferorion_error::prelude::*plus small layered imports. - When behavior changes, verify with
cargo test --all-features -- --test-threads=1from the crate root.
Current API Facts
- Package line is
0.9.x, Rust 2021. - Main runtime carrier:
StructError<R>. - New domain reason enums should usually derive
OrionErrorinstead of manually assemblingDisplay,ErrorCode,ErrorIdentityProvider, andDomainReason. - Stable external identity is
ErrorIdentity.code, not the legacy numericErrorCode. - Public protocol naming is now
Exposure*, notErrorPolicy*. StructError<R>no longer directly implementsstd::error::Error.- Standard-error ecosystem boundaries go through explicit interop APIs such as
as_std(),into_std(),into_boxed_std(), andinto_dyn_std(). - Prefer layered imports when the module benefits from explicit boundaries:
runtime::*conversion::*report::*protocol::*interop::*reason::*dev::testing::*SourceRawErr+source_raw_err(Reason, detail)accepts anyStdError, noUnstructuredSourceimpl needed. This is the escape hatch for third-party error types without a dedicated bridge (e.g.git2::Error,reqwest::Error).source_err(Reason, detail)remains the preferred path whenE: UnstructuredSource(e.g.std::io::Error,serde_json::Errorwithserde_json,tomlerrors withtoml, andanyhow::Errorwithanyhow).with_source(err)andStructErrorBuilder::source(...)are declaredpubbut bound on apub(crate)trait, so they are not callable from downstream crates. Use the downstream-callable paths instead:source_err(...)/source_raw_err(...)onResult, andStructErrorBuilder::source_std(...)/source_struct(...).- Legacy
owe(...),owe_*(),err_wrap(...),want(...), andwith(...)paths are removed from the current primary API. - Operation logging (0.9+):
OperationContextis pureClonedata with noDrop;with_auto_log()returns a non-CloneAutoLogGuardthat writes the outcome log exactly once on drop. Attach context to an error as data viawith_context(&guard). See Operation Logging (0.9).
Recommended 0.9 Workflow
- Define a domain enum with
#[derive(OrionError)]. - Give business variants stable
#[orion_error(identity = "...")]identities. - Keep a transparent
General(UnifiedReason)variant for shared infrastructure categories.
#[derive(OrionError)] exposes the full set of UnifiedReason delegate constructors on the outer enum, so prefer calls like AppReason::system_error() or AppReason::validation_error() over AppReason::from(UnifiedReason::system_error()).
- Use
OperationContext::doing(...)plus chainedwith_field(...)/with_meta(...)for structured context. - For a single domain reason turning into
StructError<R>, preferto_err(). - For a normal
Result<T, E>entering the structured system the first time, prefersource_err(reason, detail)whenE: UnstructuredSource(e.g.std::io::Error). - For third-party
StdErrortypes that don't implementUnstructuredSource(e.g.git2::Error,reqwest::Error), usesource_raw_err(reason, detail). - For an upstream
Result<T, StructError<R1>>that only changes reason type, useconv_err(). - For an upstream error where the upper layer wants a new semantic boundary, use
source_err(reason, detail). - For real underlying errors, prefer the
Result-level entry pointssource_err(...)/source_raw_err(...); when building aStructErrordirectly, useStructErrorBuilder::source_std(...)/source_struct(...). - For stable machine identity, prefer
identity_snapshot()/ErrorIdentity.code. - For protocol projection, prefer
exposure(...)/into_exposure(...)andto_*_error_json()whenserde_jsonis enabled. - For human diagnostics and redaction, prefer
report(),render(),render_redacted(...), andrender_user_debug()on protocol snapshots.
Decision Tree
- Upstream is
Result<T, E>andE: UnstructuredSource(e.g.std::io::Error, feature-enabledserde_json,toml, oranyhowerrors): usesource_err(reason, detail). - Upstream is
Result<T, E>andE: StdErrorbut NOTUnstructuredSource(e.g.git2::Error,reqwest::Error): usesource_raw_err(reason, detail). - Upstream is
Result<T, StructError<R1>>and the upper layer only remaps reason type: useconv_err(). - Upstream is
Result<T, StructError<R1>>and the upper layer wants a new semantic boundary with preserved lower structured source: usesource_err(reason, detail). - A single reason enum value needs to become a
StructError<R>: useto_err(). - You are attaching any source directly while building a
StructError: useStructErrorBuilder::source_std(...)for a rawStdErrororsource_struct(...)for a lowerStructError<_>. err_conv()is a deprecated compatibility alias forconv_err(). Old call sites will warn; new code should useconv_err().- A boundary requires
std::error::Error: useas_std(),into_std(),into_boxed_std(), orinto_dyn_std()instead of assumingStructError<R>itself is a standard error. - If you see legacy
owe(...),owe_*(),err_wrap(...),want(...), orwith(...)in examples, treat that material as stale and migrate to the current workflow.
Existing-System Migration Branch
Use this branch when upgrading an existing crate or service with old error APIs, anyhow::Result, broad map_err, or payload-carrying reason enums.
- Upgrade the
orion-errordependency and imports first. - Replace obvious legacy APIs such as
.owe(),owe_*(),into_as(...),upcast(),wrap_as(...),err_wrap(...),want(...), andwith(...). - Convert boundary errors next:
- File IO: prefer
source_err(reason, detail). - Command execution: prefer
source_err(...)for supported std errors,source_raw_err(...)for third-party process wrappers. - HTTP/download/upload: usually
source_raw_err(...)unless the error type has anUnstructuredSourcebridge. - serde/json/yaml/toml/template/render: use
source_err(...)when the crate feature provides a bridge, otherwisesource_raw_err(...). anyhow::Result: do not expandanyhowthrough core paths; with theanyhowfeature usesource_err(...), otherwise usesource_raw_err(...)if the type is a plainStdErrorboundary.
- Replace pure wrapping
map_errcalls withsource_err(...),source_raw_err(...), orconv_err(). - Keep payload-carrying reason enums temporarily during the API migration so compile errors stay focused on API changes.
- After tests stabilize, migrate domain reasons such as
RunReason,ExecReason, andGxlReasontoward unit enum variants. - Move the old payload information into
StructErrordetail, context, fields, metadata, or source chains.
Unit enum reason modeling is the semantic-convergence phase, not the first API-upgrade step. Doing it too early mixes constructor breakage with diagnostic relocation and makes migrations harder to review.
MapErr Migration Rules
- Replace pure wrappers like
foo().map_err(|e| Reason::Io.to_err().with_detail(e.to_string()))?withfoo().source_err(Reason::Io, "read config")?whenE: UnstructuredSource. - For third-party
StdErrorboundaries without a bridge, usefoo().source_raw_err(Reason::system_error(), "call http api")?. - For lower
StructError<R1>values that only need reason conversion, useconv_err(). - Keep
map_errwhen conversion contains business branching, rewrites a user-facing message, or adds structured fields/context that cannot be expressed cleanly with the chained helpers.
Domain Enum Guidance
- Prefer
#[derive(OrionError)]on enums or structs used as reasons. - Use explicit stable identities for business-facing variants.
- Model domain reasons as unit enum variants whenever possible, e.g.
Reason::InvalidInput, notReason::InvalidInput(payload). - Do not put diagnostic payloads, file paths, tenant IDs, raw backend messages, or dynamic details inside the reason value. Put them on
StructErrorwithto_err().with_detail(...),with_context(OperationContext::...with_field(...) / with_meta(...)), or thedetailargument ofsource_err(...). - Keep the
General(UnifiedReason)transparent variant to reuse shared category / retry / severity semantics. - When the variant is transparent over
UnifiedReason, prefer the generated delegate constructors (core_conf(),validation_error(),system_error(), etc.) on the outer enum. - Root-visible
ErrorCoderemains valid, but treat it as a compatibility numeric code rather than the primary external identity.
Import Guidance
- Default for new application code:
use orion_error::prelude::*;- then add small layered imports such as
runtime::OperationContext,reason::UnifiedReason,protocol::DefaultExposurePolicy, orconversion::{ToStructError, SourceErr, SourceRawErr, ConvErr} to_err()comes fromconversion::ToStructErrorand is not inprelude::*; adduse orion_error::conversion::ToStructError;wherever you call.to_err().- For operation logging, import
runtime::AutoLogGuard(the type returned byOperationContext::with_auto_log()); it is not inprelude::*. - Prefer explicit layered imports when reviewing architecture boundaries.
- Avoid broad root imports except for the small primary-path names.
dev::prelude::*is for protocol/schema tests and migration verification, not normal business modules.
Exposure, Report, Protocol
- Protocol/redaction APIs are centered on:
DefaultExposurePolicyExposurePolicyExposureDecisionErrorProtocolSnapshot- Stable identity path:
identity_snapshot()ErrorIdentity.code- Human/report path:
report()into_report()render()render_redacted(...)- Protocol projection path:
exposure(...)into_exposure(...)to_http_error_json()to_rpc_error_json()to_cli_error_json()to_log_error_json()render_user_debug()render_user_debug_redacted(...)
Operation Logging (0.9)
As of 0.9, operation logging is split into a data role and a guard role. This is the sanctioned way to emit lifecycle (suc! / fail! / cancel!) logs.
OperationContext— pure data: aClonecarrier of fields / path / result with noDropside effect.AutoLogGuard(runtime::AutoLogGuard) — an owned, non-Cloneguard created byOperationContext::with_auto_log(); it writes the outcome entry exactly once, on drop.OperationScope<'a>— a borrowed guard for marking the result (scope()/scoped_success()), usable on a bareOperationContextor through anAutoLogGuard.
Reasonable approach:
- Build the operation as pure data, then arm a guard only where you want lifecycle logging:
```rust
let ctx = OperationContext::doing("renew").with_field("gateway_id", id);
let guard = ctx.with_auto_log();
```
- For fallible flows, use
scope()(defaults to failure) plusmark_success(). An early?return skipsmark_success(), so the failure is logged correctly:
```rust
let mut guard = OperationContext::doing("renew").with_auto_log();
let mut scope = guard.scope(); // default: failure
let value = fetch().await?; // early return -> fail!
scope.mark_success(); // success -> suc!
```
Avoid scoped_success() in ?-heavy code: it defaults to success, so an early return is logged as suc!.
- To attach the operation to an error as data, borrow the guard:
err.with_context(&guard). This copies data and emits no log; the guard stays the single log owner. There is intentionally no by-valuewith_context(guard)(that would defer or repeat the log). Useguard.into_context()to disarm and keep only the data.
- Do not add
error!/info!at every layer; the model is sparse lifecycle logs plus boundary error projection.
Migration from 0.8:
with_auto_log()now returnsAutoLogGuardinstead ofOperationContext. Most call sites are unchanged becauseAutoLogGuardderefs toOperationContext(mark_suc(),scoped_success(),info(...),record(...)still work).OperationContextno longer hasDrop/exit_log; code that relied on an armedOperationContextlogging at its own drop must attach&guardinstead.- Only storing or returning
with_auto_log()'s result asOperationContextbreaks; useinto_context()there.
Features:
- Default features include
logandderive; optional features includetracing,serde,serde_json,anyhow, andtoml. - With the
tracingfeature enabled the entry goes throughtracing(preferred when bothlogandtracingare on). - See
references/logging.mdfor copyable templates and the crate'sdocs/*/src/user/autolog-guard.mdfor the full guide.
Docs And Site Guidance
- Current docs are two mdBooks:
- English:
docs/en/book.toml, source underdocs/en/src/ - Chinese:
docs/zh/book.toml, source underdocs/zh/src/ - Root
docs/index.htmlis the language selector; generated output lives undersite/en/andsite/zh/. - When writing governance/AI docs, do not claim "error-handling code is 40-60% of development work." The defensible claim is that finding/fixing bugs and avoidable rework are often cited in the 40-60% effort range, while exception/error-handling code itself is a much smaller source-code fraction in field studies.
- Keep docs concise and distinguish current 0.9 API from ideal architecture or future design notes.
Stale-Doc Guardrails
- Do not teach
thiserror-only reason enums as the preferred0.9style; prefer#[derive(OrionError)]. - Do not present
ErrorPolicy*orpolicy_*as current public APIs. - Do not assume
StructError<R>implementsstd::error::Errordirectly. - Do not recommend
owe_*()as the default path for new code. - Do not recommend
StructError::from(reason)as the default path for new code; preferto_err(). - Do not introduce data-carrying reason variants like
Reason::X(payload)for diagnostics; migrate those toReason::X.to_err().with_detail(payload)or preserve the dynamic information in thesource_err(reason, detail)detail/context path. - Do not recommend
into_as(...); usesource_err(...). - Do not recommend
upcast(); useconv_err(). - Do not recommend
wrap_as(...)orErrorWrapAs; that API has been removed and semantic-boundary wrapping now goes throughsource_err(...). - Do not recommend
err_conv()as the primary conversion path; preferconv_err(). with_std_source(...)/with_struct_source(...)arepub(crate);with_source(...)andbuilder.source(...)are also not downstream-callable (private trait bound). Prefersource_err(...)/source_raw_err(...)orStructErrorBuilder::source_std(...)/source_struct(...).- Do not recommend
AppReason::from(UnifiedReason::...)as the default way to build a transparentUnifiedReasonvariant; prefer the derived delegate constructor on the outer enum. - Do not route a
StructError<_>through legacyinto_as(...); usesource_err(...)when intentionally preserving it as a source under a new reason. - Do not treat
ErrorCodeas the primary external identity; use stable identity /ErrorIdentity.code. - Do not recommend public field-name constants for report/protocol JSON shapes; these are not part of the stable public API.
- Do not teach
OperationContextas aDrop-based logger; as of 0.9 auto-logging is owned by the non-CloneAutoLogGuard. - Do not reference the removed
OperationContext::exit_log()/exit_logfield. - Do not recommend attaching an armed
OperationContextto an error to log at error-drop; attach&guardfor data only (or useinto_context()to disarm). - Do not recommend
scoped_success()for?-heavy flows; preferscope()+mark_success(). - If docs disagree with
src/, tests, or examples inorion-error, follow the source and tests.
References
Read references/patterns.md when you need copyable Rust templates, and references/logging.md for the sanctioned 0.9 operation-logging patterns.