gix_error/lib.rs
1//! Common error types and utilities for error handling.
2//!
3//! # Classification and recovery
4//!
5//! Error classification matters because it lets a generic caller **choose a recovery approach**,
6//! supporting resilient software.
7//! Classes describe different remedies, not just different wording:
8//!
9//! | [`Class`] | Recovery approach |
10//! | --- | --- |
11//! | [`Cancelled`](Class::Cancelled) | Stop; preserve the caller's intent instead of automatically retrying. |
12//! | [`Corruption`](Class::Corruption) | Repair, replace, or re-fetch malformed data. |
13//! | [`ResourceExhaustion`](Class::ResourceExhaustion) | Reduce usage, adjust a limit, or free capacity. |
14//! | [`Validation`](Class::Validation) | Correct the caller's input. |
15//! | [`Unsupported`](Class::Unsupported) | Switch implementation, capability, format, protocol, or strategy. |
16//! | [`Unauthenticated`](Class::Unauthenticated) | Obtain or refresh credentials, distinct from authenticated-but-forbidden. |
17//! | [`PermissionDenied`](Class::PermissionDenied) | Obtain authorization or change permissions. |
18//! | [`Conflict`](Class::Conflict) | Refresh or reconcile state before retrying against the new state. |
19//! | [`NotFound`](Class::NotFound) | Create the resource, use a fallback, or accept absence. |
20//! | [`Retryable`](Class::Retryable) | Consider a bounded retry, possibly after waiting. |
21//!
22//! The table follows [`Class`]'s suggested recovery precedence, highest first. [`Error::dominant_class()`]
23//! and [`Exn::dominant_class()`] return the highest-precedence class present, or `None` for unclassified errors.
24//! For borrowed errors, use [`classify()`] followed by [`dominant_class()`](types::Classifications::dominant_class).
25//! This uses the smallest [`Class`] under its ordering, rather than the first classification in traversal order.
26//!
27//! **A class guides recovery; it does not establish that recovery is safe.** An operation whose outcome is
28//! unknown may already have performed side effects, so retrying can duplicate them even after a transient failure.
29//! Inspect concrete recovery errors and partial outcomes when necessary. Multiple causes can suggest different
30//! remedies; a matching class does not make sibling failures ignorable. Both retry policies reject explicit
31//! cancellation anywhere in the inspected causes; [`Error::is_retryable()`] only reports whether a retryable cause exists.
32//!
33//! Leave errors unclassified when the remedy is unknown. An external program's failed exit status alone does not
34//! establish a class. Preserve genuine callee errors rather than assigning their context an unsupported guess.
35//! Classify intrinsic conditions at their definition; use [`tag()`] for context-dependent classifications.
36//!
37//! # Usage
38//!
39//! Use [`Result`] and [`Error`] for public APIs with erased or message-based errors in plumbing crates and in `gix`.
40//! Public traits, callbacks, iterator items, associated errors, and re-exported APIs follow the same rule.
41//! It's Ok to preserve concrete error types already exposed by public signatures, including
42//! [`ExnResult<T, Specific>`](ExnResult) and [`Exn<Specific>`](Exn), if this helps readability and consumers.
43//! Native `std::io::Result`, standalone concrete-error results, and generic error adapters can retain their types.
44//!
45//! Private and `pub(crate)` implementations also use [`Result`] for erased or message-based errors.
46//! Retain concrete errors when callers benefit from typed recovery or payload access. Use [`ExnResult<T, E>`](ExnResult)
47//! or [`ExnMessageResult<T>`](ExnMessageResult) when callers need a specific exception type or manipulate exception trees.
48//!
49//! The default helpers return [`Error`] and [`Result`]; their `_typed` variants retain an [`Exn<E>`](Exn):
50//!
51//! | Default helper | Typed exception helper |
52//! |---------------|------------------------|
53//! | [`ErrorExt::raise()`] | [`ErrorExt::raise_typed()`] |
54//! | [`ErrorExt::and_raise()`] | [`ErrorExt::and_raise_typed()`] |
55//! | [`ResultExt::or_raise()`] | [`ResultExt::or_raise_typed()`] |
56//! | [`OptionExt::ok_or_raise()`] | [`OptionExt::ok_or_raise_typed()`] |
57//!
58//! Use [`ResultExt::or_error()`] to convert native errors or exceptions to [`Result`] without adding context.
59//! Existing [`Error`] values pass through unchanged. Conversions preserve concrete recovery errors, causes,
60//! metadata, and caller locations; `?`, `.into()`, and [`Exn::into_error()`] also convert exceptions to [`Error`].
61//! Use [`Error::into_exn()`] to recover an exception tree for internal processing, including rearranging child frames.
62//!
63//! # Caller locations
64//!
65//! The `error-print-location` feature enables caller locations in diagnostics. Paths with conventional
66//! `src`, `tests`, `examples`, or `benches` directories are shortened to the containing package directory
67//! and source path; Cargo registry package versions are omitted. For example,
68//! `/home/user/.cargo/registry/src/index.crates.io-hash/gix-url-0.39.0/src/parse.rs:349`
69//! is displayed as `gix-url/src/parse.rs:349`. Package-relative source paths are retained;
70//! paths whose package root cannot be inferred from these directory conventions fall back to the filename.
71//! Displayed paths use forward slashes on every platform.
72//!
73//! This only changes formatting: inspected locations retain the compiler-provided file, line, and column.
74//! A location contains no Cargo package metadata, so a directory that differs from the package name cannot
75//! be renamed automatically. Build owners can use rustc's `--remap-path-prefix` to control captured paths
76//! for arbitrary source layouts. Alternate formatting continues to omit locations.
77//!
78//! # Standard Error Types
79//!
80//! Use these types for diagnostic context when recovery does not depend on a specific condition or structured payload.
81//! Otherwise retain a concrete [`Error`](std::error::Error)-implementing type, and use it with
82//! [`ResultExt::or_raise(<StandardErrorType>)`](ResultExt::or_raise) or
83//! [`OptionExt::ok_or_raise(<StandardErrorType>)`](OptionExt::ok_or_raise), or sibling methods.
84//!
85//! All these types implement [`Error`](std::error::Error).
86//!
87//! ## [`Message`] and [`ClassificationMarker`]
88//!
89//! [`Message`] combines a diagnostic message, an optional [`Class`], and named scalar values. Use it
90//! for diagnostic context, or instead of a chain of type-bearing errors when those layers only describe a single
91//! failure. Keep concrete errors when callers need to match a particular condition, even without a payload.
92//! [`not_found()`], [`validation()`], [`corruption()`], [`retryable()`], [`resource_exhaustion()`],
93//! [`allocation_limit()`], [`allocation_failure()`], [`cancelled()`], [`permission_denied()`],
94//! [`unauthenticated()`], [`conflict()`], and [`unsupported()`] construct classified messages.
95//! [`message()`] and [`Message::new()`] start without a class or values. [`Message::with_class()`] and
96//! [`Message::with()`] add them to the same diagnostic. Use [`message!`] for formatting, equivalent to
97//! [`Message::new(format!("…"))`](Message::new) or `format!("…").into()`.
98//! [`Message::corrupted()`] and [`Message::validation()`] are shortcuts for [`Class::Corruption`] and [`Class::Validation`],
99//! respectively: `message!("invalid record at {offset}").corrupted()` or `message!("invalid count: {count}").validation()`.
100//! The other classes have matching builders: [`Message::not_found()`], [`Message::retryable()`],
101//! [`Message::resource_exhaustion()`], [`Message::allocation_limit()`], [`Message::allocation_failure()`],
102//! [`Message::cancelled()`], [`Message::permission_denied()`], [`Message::unauthenticated()`],
103//! [`Message::conflict()`], and [`Message::unsupported()`].
104//! [`Message::corrupted_error()`], [`Message::validation_error()`], [`Message::not_found_error()`], [`Message::retryable_error()`],
105//! [`Message::resource_exhaustion_error()`], [`Message::allocation_limit_error()`], [`Message::allocation_failure_error()`],
106//! [`Message::cancelled_error()`], [`Message::permission_denied_error()`], [`Message::unauthenticated_error()`],
107//! [`Message::conflict_error()`], and [`Message::unsupported_error()`]
108//! combine these builders with [`ErrorExt::raise()`] when an [`Error`] is needed directly.
109//! Prefer [`corruption()`] or [`validation()`] for static messages when more concise.
110//!
111//! Classification does not determine which diagnostic values can be attached. For example,
112//! `corruption("Malformed reference").with_input(bytes)` preserves offending bytes in the same
113//! error that describes their corruption. No extra validation error is needed just to store input.
114//! Use explicit classified constructors or builders: converting a string to [`Message`] does not infer a class
115//! from the function's return type.
116//!
117//! | Type | Diagnostic | Classification | Purpose |
118//! |------|------------|----------------|---------|
119//! | [`Message`] | Visible message and optional values | Optional | Describe a failure without a custom error type |
120//! | [`ClassificationMarker`] | Transparent, no diagnostic of its own | Required | Classify an existing error while preserving its concrete type |
121//!
122//! ```
123//! use gix_error::{ErrorExt, Message, MetadataValue};
124//!
125//! let error = gix_error::not_found("Reference does not exist")
126//! .with("path", std::path::Path::new("HEAD"))
127//! .raise();
128//! assert!(error.is_not_found());
129//! assert!(error.probable_cause().is::<Message>());
130//! assert_eq!(error.metadata().next().expect("lookup details")["path"], MetadataValue::Path("HEAD".into()));
131//! ```
132//!
133//! Callers should add context using information they already possess and document its keys on the function
134//! that returns it. Preserve real callee errors, especially concrete recovery signals and complex results
135//! discovered by the callee, such as partial outcomes:
136//!
137//! ```
138//! use gix_error::{message, ResultExt, Message, MetadataValue};
139//!
140//! let error = Err::<(), _>(std::io::Error::from(std::io::ErrorKind::NotFound))
141//! .or_raise(|| message("Could not read reference").with("path", std::path::Path::new("HEAD")))
142//! .expect_err("the lookup failed");
143//! assert!(error.is_not_found());
144//! assert!(error.probable_cause().is::<std::io::Error>());
145//! let context = error.error().downcast_ref::<Message>().expect("message context");
146//! assert_eq!(context.class, None, "the callee, not the context, supplies the classification");
147//! let values = error.metadata().next().expect("lookup context");
148//! assert_eq!(values["path"], MetadataValue::Path("HEAD".into()));
149//! ```
150//!
151//! [`Exn::metadata()`] and [`Error::metadata()`] yield each message's non-empty [`Metadata`] dictionary in error traversal order.
152//! Each dictionary maps names to [`MetadataValue`]s. Keys are local to their context. Use [`Exn::metadata_merged()`] or
153//! [`Error::metadata_merged()`] to obtain one owned dictionary, with more specific causes overriding enclosing contexts.
154//! Merging independent causes discards their origin; later-visited values win. [`Metadata`] documents common schemas
155//! for input validation and external program runtime failures.
156//! These conventions do not require collecting additional information or imply a classification.
157//! Metadata is printed without redaction and may expose personally identifiable information (PII) or secrets;
158//! see [metadata privacy](Metadata#privacy), especially before opting into [`Message::with_command()`].
159//! To identify a specific failure without inspecting its values, see
160//! [matching a specific failure](#matching-a-specific-failure).
161//!
162//! # [`Exn<ErrorType>`](Exn) and [`Exn`]
163//!
164//! The [`Exn`] type does not implement [`Error`](std::error::Error) itself, but is able to store causing errors
165//! via [`ResultExt::or_raise_typed()`] (and sibling methods) as well as location information of the creation site.
166//!
167//! Use exceptions in helpers whose callers need a typed context or tree operations such as [`Exn::chain_all()`].
168//! [`Exn::erased`] and [`ExnResult<T>`](ExnResult) let these helpers combine different exception types.
169//! Other helpers use [`Result`], which retains causes and locations without conversions at each caller.
170//! Preserve concrete public exception signatures.
171//!
172//! Propagate existing [`Error`] values directly with `?` when the callee already provides enough context.
173//! Use `.or_raise(|| message("context information"))` or its siblings when added context helps diagnose
174//! the failure, explains the operation's purpose, or identifies user-controlled input such as configuration values.
175//! Keep such context even when failures are rare, then errors serve as in-code explanation and intent.
176//!
177//! # Callback results
178//!
179//! Public and private callbacks with erased or message-based errors use [`Result<T>`](Result); concrete callback errors
180//! retain their types. Add context with
181//! [`ResultExt::or_raise()`] when propagating a callback failure:
182//! ```
183//! use gix_error::{message, Result, ResultExt};
184//!
185//! fn parse_count(input: &str) -> Result<u64> {
186//! input.parse::<u64>().or_raise(|| message("could not parse count"))
187//! }
188//!
189//! pub fn process(callback: impl FnOnce() -> Result<u64>) -> Result<u64> {
190//! callback().or_raise(|| message("callback failed"))
191//! }
192//!
193//! assert_eq!(process(|| parse_count("42"))?, 42);
194//! # Ok::<(), gix_error::Error>(())
195//! ```
196//!
197//! Private callbacks that need exception-tree operations may use [`ExnResult`] or [`ExnMessageResult`].
198//! Use [`ResultExt::or_erased()`] only when such a callback requires an erased exception.
199//!
200//! # [`Error`] — `Exn` with `std::error::Error`
201//!
202//! Since [`Exn`] does not implement [`std::error::Error`], it cannot be used where that trait is required
203//! (e.g. `std::io::Error::other()`, or as a `#[source]` in another error type).
204//! The [`Error`] type bridges this gap: it implements [`std::error::Error`] and converts from any
205//! [`Exn<E>`](Exn) via [`From`], preserving the full error tree and location information.
206//!
207//! ```rust,ignore
208//! // Convert an Exn to something usable as std::error::Error:
209//! let exn: Exn<Message> = message("something failed").raise_typed();
210//! let err: gix_error::Error = exn.into();
211//! let err: gix_error::Error = exn.into_error();
212//!
213//! // Useful where std::error::Error is required:
214//! std::io::Error::other(exn.into_error())
215//! ```
216//!
217//! It can also be created directly from any `std::error::Error` via [`Error::from_error()`], which preserves
218//! native formatting for tree-backed errors. For native-error results, prefer [`ResultExt::or_error()`]
219//! to capture the caller location and use exception formatting.
220//! When a constructor is needed, invoke it in a closure, e.g. `.map_err(|err| Error::from_boxed(err))`.
221//! Passing the constructor directly to an adapter captures a `FnOnce` shim's location instead of the call site.
222//!
223//! # Tests with [`TestResult`]
224//!
225//! Return [`TestResult`] from `#[test]` functions to propagate ordinary errors, [`Exn<E>`](Exn), and [`Error`]
226//! directly with `?`. It defaults to `Result<(), TestError>`; helpers returning a value can use `TestResult<T>`.
227//! Accepted errors must convert into `Box<dyn std::error::Error + Send + Sync + 'static>`.
228//!
229//! When a test returns an error, Rust's test harness prints [`TestError`]'s [`Debug`](std::fmt::Debug) output,
230//! including the complete diagnostic tree or chain. Captured caller locations are printed when the
231//! `error-print-location` feature is enabled; alternate formatting omits them.
232//!
233//! ```rust,test_harness
234//! use gix_error::{message, ResultExt, TestResult};
235//!
236//! #[test]
237//! fn parses_count() -> TestResult {
238//! let expected: usize = "42".parse()?;
239//! let actual = "42".parse::<usize>().or_raise(|| message("could not parse count"))?;
240//! assert_eq!(actual, expected, "context preserves the parsed count");
241//! Ok(())
242//! }
243//! ```
244//!
245//! # Migrating from `thiserror`
246//!
247//! This section describes the mechanical translation from `thiserror` error enums to `gix-error`.
248//! In `Cargo.toml`, replace `thiserror = "<version>"` with `gix-error = { version = "^0.1.0", path = "../gix-error" }`.
249//!
250//! ## Choosing the replacement type
251//!
252//! Use [`Result`] for diagnostic messages, including validation failures without callee errors, in public and private code.
253//! [`Message`] carries an optional class and named scalar values; [`Error`] retains the diagnostic context and causes.
254//! Keep a concrete error type in [`ExnResult`] when recovery requires a specific condition or structured payload.
255//! Public trait associated types also use [`Error`] for message-based errors, including bare [`Message`] errors.
256//! Preserve concrete public exception signatures. Internal results retain [`ExnMessageResult`] or [`ExnResult`] when
257//! callers need a specific exception type or exception-tree operations.
258//! Define at most one operation-specific error type, normally a public, `#[non_exhaustive]` enum named `Error`.
259//! Related methods should share it. Broad [`Class`] values categorize errors; variants
260//! define specific recovery decisions. Preserve genuine callee errors as causes instead of formatting them into text.
261//!
262//! Use the chosen type directly in signatures, importing it under its canonical name where helpful.
263//! Crate-specific and operation-specific forwarding aliases or renamed error exports are unnecessary.
264//! Facades may re-export the canonical types, as `gix` does with `Error`, `Exn`, `Result`, `ExnResult`, and `ExnMessageResult`.
265//! Always import the result aliases directly and use their bare names in signatures.
266//!
267//! ## Translating variants
268//!
269//! Translate variants to messages only when they provide diagnostics without a specific recovery contract.
270//! Use [`.raise()`](ErrorExt::raise) to wrap standalone errors into an [`Error`], and
271//! [`ResultExt::or_raise()`] to preserve callee errors with additional context.
272//! For early returns, use [`bail!`] with a concrete error, message, or format arguments, such as
273//! `bail!(Error::SomethingFailed)`, `bail!(message("something went wrong"))`, or `bail!("invalid input: {input}")`.
274//! Prefer to import `bail` with `use gix_error::bail;` (or `use gix::error::bail;` in applications) and
275//! invoke it as `bail!(...)` instead of using a qualified path.
276//! String shorthand is unclassified unless a builder supplies a class. In plumbing APIs, classify known input or data failures explicitly, e.g.
277//! `bail!(validation("invalid input"))` or `bail!("invalid record at {offset}".corrupted())`.
278//! To add context when returning [`Result`], use `bail!(err.and_raise(message("context")))`;
279//! reserve [`ErrorExt::and_raise_typed()`] for [`ExnResult`]s that require an exception type.
280//! When passing an existing [`Exn`], keep any context and explicit erasure inside the macro;
281//! propagating an existing public [`Error`] should use `return Err(err)`.
282//!
283//! **Static message variant:**
284//! ```rust,ignore
285//! // BEFORE:
286//! #[error("something went wrong")]
287//! SomethingFailed,
288//! // → Err(Error::SomethingFailed)
289//!
290//! // AFTER (returning gix_error::Result):
291//! // → Err(message("something went wrong").raise())
292//! ```
293//!
294//! **Formatted message variant:**
295//! ```rust,ignore
296//! // BEFORE:
297//! #[error("unsupported format '{format:?}'")]
298//! Unsupported { format: Format },
299//! // → Err(Error::Unsupported { format })
300//!
301//! // AFTER (returning gix_error::Result):
302//! // → Err(message!("unsupported format '{format:?}'").raise())
303//! ```
304//!
305//! **`#[from]` / `#[error(transparent)]` variant** without a recovery contract — delete the forwarding variant;
306//! at each call site, use [`ResultExt::or_raise()`] to add context:
307//! ```rust,ignore
308//! // BEFORE:
309//! #[error(transparent)]
310//! Io(#[from] std::io::Error),
311//! // → something_that_returns_io_error()? // auto-converted via From
312//!
313//! // AFTER (the variant is deleted):
314//! // → something_that_returns_io_error()
315//! // .or_raise(|| message("context about what failed"))?
316//! ```
317//!
318//! **`#[source]` variant with diagnostic context only** — use [`ResultExt::or_raise()`]:
319//! ```rust,ignore
320//! // BEFORE:
321//! #[error("failed to parse config")]
322//! Config(#[source] config::Error),
323//! // → Err(Error::Config(err))
324//!
325//! // AFTER:
326//! // → config_call().or_raise(|| message("failed to parse config"))?
327//! ```
328//!
329//! **Guard / assertion** — use [`ensure!`]:
330//! ```rust,ignore
331//! // BEFORE:
332//! if !condition {
333//! return Err(Error::SomethingFailed);
334//! }
335//!
336//! // AFTER (returning Exn<Message>, with a validation class):
337//! ensure!(condition, gix_error::validation("something went wrong"));
338//!
339//! // AFTER (returning Exn<Message>):
340//! ensure!(condition, message("something went wrong"));
341//! ```
342//!
343//! ## Updating the function signature
344//!
345//! When replacing a diagnostic-only error enum, change the return type and add the necessary imports:
346//! ```rust,ignore
347//! // BEFORE:
348//! fn parse(input: &str) -> Result<Value, Error> { ... }
349//!
350//! // AFTER (public or private):
351//! use gix_error::{message, ErrorExt, Result, ResultExt};
352//! fn parse(input: &str) -> Result<Value> { ... }
353//! ```
354//! Public APIs that already expose a concrete error, such as `ExnResult<Value, SpecificError>`, retain that type.
355//!
356//! ## Updating tests
357//!
358//! Tests of diagnostic wording can use string assertions:
359//! ```rust,ignore
360//! assert_eq!(result.expect_err("the operation fails").to_string(), "something went wrong");
361//! ```
362//! Keep variant assertions for recovery contracts, and test structured payloads directly.
363//!
364//! For semantic checks, both [`Exn`] and [`Error`] provide [`is_retryable()`](Exn::is_retryable),
365//! [`is_not_found()`](Exn::is_not_found), [`is_validation()`](Exn::is_validation),
366//! [`is_corrupted()`](Exn::is_corrupted), [`is_resource_exhausted()`](Exn::is_resource_exhausted),
367//! [`is_cancelled()`](Exn::is_cancelled), [`is_permission_denied()`](Exn::is_permission_denied),
368//! [`is_unauthenticated()`](Exn::is_unauthenticated), [`is_conflict()`](Exn::is_conflict), and
369//! [`is_unsupported()`](Exn::is_unsupported).
370//! These inspect causes as well as the outermost error. `is_retryable()` requires an explicit retry classification;
371//! [`Exn::can_retry()`] and [`Error::can_retry()`] additionally recognize certain I/O error kinds.
372//! I/O errors with kind `NotFound`, `OutOfMemory`, `PermissionDenied`, or `Unsupported` receive corresponding
373//! semantic classifications; other kinds remain unclassified. For legacy credential-challenge I/O wrappers,
374//! an explicit [`Class::Unauthenticated`] anywhere in a `PermissionDenied` payload takes precedence over that
375//! wrapper's native permission classification. The original I/O error remains available for downcasting;
376//! independently classified permission causes in its payload remain visible.
377//! `Interrupted` alone does not establish caller cancellation.
378//! Retry predicates also inspect original I/O kinds, but explicit cancellation takes precedence.
379//!
380//! For application-level cancellation, use [`cancelled()`]. Preserve genuine I/O errors as causes.
381//! Classification itself neither clears interruption state nor retries.
382//! ```
383//! use gix_error::ErrorExt;
384//!
385//! let err = gix_error::cancelled("Cancelled by user").raise();
386//! assert!(err.is_cancelled());
387//! assert!(!err.can_retry());
388//! assert!(!err.can_retry_lenient());
389//! ```
390//!
391//! Use [`Exn::probable_cause()`] to inspect the likely root cause. It follows a single causal path, stopping at the
392//! first branch rather than choosing an arbitrary sibling. Classification markers are transparent to this selection.
393//! [`Exn::classify()`] and [`Error::classify()`] expose each known classification together with its original error.
394//! Custom payloads of [`std::io::Error`] are inspected too, including any nested [`Error`] trees.
395//!
396//! [`Message`] supplies its own diagnostic and optional classification. In contrast, [`ClassificationMarker`]
397//! only supplies classification metadata. Prefer defining intrinsic classifications on error types you control:
398//!
399//! * For a leaf error or variant whose classification is part of its meaning, return a constant marker from
400//! [`std::error::Error::source()`]. This makes every construction site carry the classification without repeated
401//! [`tag()`] calls.
402//! * Use [`tag()`] when a classification depends on the calling context, or when you cannot modify the error type.
403//! It preserves the concrete error and its diagnostic.
404//!
405//! For example, a caller may know that an `AlreadyExists` I/O error is retryable in its operation:
406//! ```
407//! use gix_error::{Class, ClassificationMarker, ErrorExt, tag};
408//!
409//! let err = tag(
410//! std::io::Error::from(std::io::ErrorKind::AlreadyExists),
411//! Class::Retryable,
412//! ).raise();
413//! assert!(err.is_retryable());
414//! assert!(err.probable_cause().is::<std::io::Error>());
415//! assert!(err.downcast_any_ref::<ClassificationMarker>().is_none());
416//! let classification = err.classify().next().expect("the tag is first");
417//! assert!(classification.error().is::<std::io::Error>());
418//! assert_eq!(classification.io_kind(), Some(std::io::ErrorKind::AlreadyExists));
419//! ```
420//!
421//! Custom error types preserve classifications by exposing their immediate cause as `Some(inner)` from
422//! [`std::error::Error::source()`]. Forwarding to `inner.source()` instead can hide a classification carried by
423//! `inner` itself. A custom leaf error can borrow a constant such as [`ClassificationMarker::NOT_FOUND`]
424//! as its source to preserve its classification without defining a static or adding a generic category to its diagnostic:
425//! ```
426//! use gix_error::{ClassificationMarker, ErrorExt};
427//!
428//! #[derive(Debug)]
429//! struct MissingObject;
430//!
431//! impl std::fmt::Display for MissingObject {
432//! fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433//! f.write_str("the requested object is missing from the object database")
434//! }
435//! }
436//!
437//! impl std::error::Error for MissingObject {
438//! fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
439//! Some(const { &ClassificationMarker::NOT_FOUND })
440//! }
441//! }
442//!
443//! let err = MissingObject.raise();
444//! assert!(err.is_not_found());
445//! assert!(err.probable_cause().is::<MissingObject>());
446//! assert!(err.classify().next().expect("a classified owner").error().is::<MissingObject>());
447//! ```
448//! Use classification predicates rather than downcasting to [`Message`] just to recognize
449//! a category: diagnostic iterators and downcasts skip all classification markers. Exception and test reports
450//! omit their wrappers too, while raw [`std::error::Error::source()`] chains retain them. Genuine classified errors
451//! remain causal and can still be downcast to inspect their payloads. When storing an [`Exn`] in a custom error, convert it with
452//! [`Exn::into_error()`] so the source can expose its complete tree.
453//!
454//! Record offending input with [`Message::with_input()`], then inspect the documented [metadata](Exn::metadata()) key:
455//! ```
456//! use gix_error::{ErrorExt, MetadataValue};
457//!
458//! let err = gix_error::validation("invalid input").with_input(b"bad".as_slice()).raise();
459//! let values = err.metadata().find(|values| values.contains_key("input")).expect("input context");
460//! assert_eq!(values["input"], MetadataValue::Bytes(b"bad".as_slice().into()));
461//! ```
462//!
463//! ## Matching a specific failure
464//!
465//! Downcast to the operation's error enum and match a variant when a broad category such as [`Class::NotFound`]
466//! isn't specific enough for recovery. The enum retains structured data and identifies the condition independently
467//! of diagnostic wording. For intrinsic classifications on leaf variants of an enum you define, prefer an exhaustive
468//! match on `self` in [`std::error::Error::source()`], returning a constant marker as below. Each new variant then
469//! requires an explicit classification choice. Wrapping, erasure, and conversion to [`Error`] preserve the
470//! classification, so callers do not need to repeat it with [`tag()`].
471//!
472//! ```
473//! use gix_error::{ErrorExt, message};
474//!
475//! mod merge {
476//! use gix_error::ClassificationMarker;
477//!
478//! #[derive(Debug)]
479//! #[non_exhaustive]
480//! pub enum Error {
481//! MissingBinaryMergeResult,
482//! }
483//!
484//! impl std::fmt::Display for Error {
485//! fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
486//! match self {
487//! Self::MissingBinaryMergeResult => f.write_str("The binary merge result could not be selected"),
488//! }
489//! }
490//! }
491//! impl std::error::Error for Error {
492//! fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
493//! match self {
494//! Self::MissingBinaryMergeResult => Some(const { &ClassificationMarker::NOT_FOUND }),
495//! }
496//! }
497//! }
498//! }
499//!
500//! fn recover(err: gix_error::Error) -> gix_error::Result<()> {
501//! match err.downcast_any_ref::<merge::Error>() {
502//! Some(merge::Error::MissingBinaryMergeResult) => Ok(()), // Apply the caller's fallback.
503//! _ => Err(err), // Preserve unfamiliar variants and all other errors.
504//! }
505//! }
506//!
507//! let err = merge::Error::MissingBinaryMergeResult.and_raise(message("Tree merge failed"));
508//!
509//! assert!(err.is_not_found(), "the variant supplies its intrinsic classification");
510//! assert!(
511//! matches!(err.downcast_any_ref::<merge::Error>(), Some(merge::Error::MissingBinaryMergeResult)),
512//! "the classified variant remains available for recovery"
513//! );
514//! recover(err)?;
515//! # Ok::<(), gix_error::Error>(())
516//! ```
517//!
518//! Downcasting and [`types::Classification::error()`] retain concrete subjects through contexts and [`Error`] conversion.
519//! Matching one cause does not make other failures in an aggregate ignorable.
520//!
521//! # Common Pitfalls
522//!
523//! ## Don't use `.erased()` to change the `Exn` type parameter
524//!
525//! [`Exn::raise()`] already nests the current `Exn<E>` as a child of a new `Exn<T>` without prior erasure.
526//! On native errors, use [`ErrorExt::and_raise()`] for an [`Error`], or
527//! [`ErrorExt::and_raise_typed()`] for a typed exception.
528//!
529//! Use [`.erased()`](Exn::erased) when you need a type-erased `Exn` (no type parameter),
530//! e.g. when combining different failures in an exception tree. Otherwise return [`Result<T>`](Result).
531//!
532//! ## Don't use `.raise_all()` with a single error
533//!
534//! [`Exn::raise_all()`] is meant for creating error trees with *multiple* causes.
535//! If you only have a single causing error, use [`.or_raise()`](ResultExt::or_raise) instead:
536//! ```rust,ignore
537//! // WRONG — raise_all() is for multiple causes, not a single one:
538//! result.map_err(|e| message("context").raise_all(Some(e.raise_typed())))?;
539//!
540//! // RIGHT — or_raise() wraps the error with context directly:
541//! result.or_raise(|| message("context"))?;
542//! ```
543//!
544//! ## Avoid conversions between diagnostic-only helpers
545//!
546//! Use [`Result`] throughout a call chain unless callers need typed exceptions or exception-tree operations.
547//! Helpers can then return their callee's result directly:
548//! ```
549//! use gix_error::{message, Result, ResultExt};
550//!
551//! fn parse_count(input: &str) -> Result<u64> {
552//! input.parse::<u64>().or_raise(|| message("could not parse count"))
553//! }
554//!
555//! pub fn count(input: &str) -> Result<u64> {
556//! parse_count(input)
557//! }
558//! assert_eq!(count("42")?, 42);
559//! # Ok::<(), gix_error::Error>(())
560//! ```
561//! Concrete public exception signatures remain typed. Use [`ResultExt::or_error()`] when a callee returns such
562//! an exception and the caller returns [`Result`]. [`Error`] implements [`std::error::Error`]; [`Exn`] does not.
563//!
564//! # Supporting types
565//!
566//! Frequently used error types, extension traits, result aliases, and constructors are available at the crate root.
567//! Utility types for flattened chains, classification, and diagnostic display live in [`types`]. Exception frames
568//! and the default type-erasure marker live in [`exn`]; [`Exn`] and its extension traits are only exported at the root.
569//!
570//! # Feature Flags
571#![cfg_attr(
572 all(doc, feature = "document-features"),
573 doc = ::document_features::document_features!()
574)]
575//! # Why not `anyhow`?
576//!
577//! `anyhow` is a proven and optimized library, and it would certainly suffice for an error-chain based approach
578//! where users are expected to downcast to concrete types.
579//!
580//! What's missing though is `track-caller` which will always capture the location of error instantiation, along with
581//! compatibility for error trees, which are happening when multiple calls are in flight during concurrency.
582//!
583//! [`Exn`] intentionally does not implement `std::error::Error`; the default helpers return [`Error`], which does.
584//!
585//! `exn` is much less optimized, but also costs only a `Box` on the stack,
586//! which in any case is a step up from `thiserror` which exposed a lot of heft to the stack.
587#![deny(missing_docs, unsafe_code)]
588pub mod exn;
589pub mod types;
590
591#[cfg(feature = "bstr")]
592pub use bstr;
593pub use exn::{
594 ext::{BoxedResultExt, ErrorExt, OptionExt, ResultExt},
595 impls::Exn,
596};
597
598/// An error type that wraps an inner type-erased boxed `std::error::Error` or an `Exn` frame.
599///
600/// In that, it's similar to `anyhow`, but with support for tracking the call site and trees of errors.
601///
602/// # Native error sources
603///
604/// [`Error::from_error()`] retains the concrete error and its native [`source()`](std::error::Error::source) chain.
605/// Use [`Error::downcast_any_ref()`] or [`Error::iter_errors()`] to inspect the original types, including sources
606/// within nested [`Error`] values. This also applies when the `auto-chain-error` feature is enabled.
607///
608/// In tree mode, standard [`source()`](std::error::Error::source) traversal prefers the stored error's native source; otherwise it follows the
609/// first explicitly raised child. Nonleaf explicit children are exposed through owning source boundaries so traversal
610/// retains their descendants. These boundaries display only their current diagnostic, including with alternate Display,
611/// while explicit leaves and native sources retain their raw concrete payloads. Raw standard-source downcasts can thus
612/// encounter wrappers; use [`Error::downcast_any_ref()`] or [`Error::iter_errors()`] for typed inspection of the complete
613/// tree. Standard traversal follows one path, not every branch; use [`Exn::into_chain()`] for a flattened source chain.
614///
615/// # The `auto-chain-error` feature
616///
617/// If it's enabled, this type is merely a wrapper around [`ChainedError`](types::ChainedError). This happens automatically
618/// so applications that require this don't have to go through an extra conversion.
619/// Standard [`source()`](std::error::Error::source) traversal skips classification markers while retaining them for classification and tree recovery.
620///
621/// When both the `tree-error` and `auto-chain-error` features are enabled, the `tree-error`
622/// behavior takes precedence and this type uses the tree-based representation.
623///
624/// With `auto-chain-error`, [`Debug`](std::fmt::Debug) reports the complete diagnostic chain,
625/// so returning [`Result`] from `main()` retains the underlying causes. Caller locations are printed only with the
626/// `error-print-location` feature, including for errors returned from `main()`. Alternate Debug (`{error:#?}`) omits them.
627/// Reports use `Caused by:` for both flattened siblings and genuine causal chains, so enabling auto-chaining makes
628/// them visually indistinguishable.
629/// See [`Exn`]'s visualization examples for the tree, flattened, and genuine-chain layouts.
630/// Normal [`Display`](std::fmt::Display) shows the root diagnostic; alternate Display (`{error:#}`) joins the
631/// complete chain with `: ` and omits locations, suitable for single-line error messages.
632///
633/// # The `anyhow` feature
634///
635/// This enables direct conversion from [`Exn`] to `anyhow::Error`, including with `?`. That conversion
636/// automatically flattens the tree into a breadth-first chain, preserving concrete error types and caller locations,
637/// regardless of `auto-chain-error` or `tree-error`. It does not change this type's representation.
638/// Converting to [`Error`] first and then wrapping it in `anyhow` follows its standard [`source()`](std::error::Error::source) chain instead:
639/// one path in tree mode, or all branches with `auto-chain-error` unless `tree-error` overrides it.
640pub struct Error {
641 #[cfg(any(feature = "tree-error", not(feature = "auto-chain-error")))]
642 inner: error::Inner,
643 #[cfg(all(feature = "auto-chain-error", not(feature = "tree-error")))]
644 inner: types::ChainedError,
645}
646
647fn root_error_eq(mut error: &(dyn std::error::Error + 'static), other: &str) -> bool {
648 while let Some(nested) = error.downcast_ref::<Error>() {
649 error = nested.error();
650 }
651 error.to_string() == other
652}
653
654impl PartialEq<str> for Error {
655 fn eq(&self, other: &str) -> bool {
656 root_error_eq(self.error(), other)
657 }
658}
659
660impl PartialEq<&str> for Error {
661 fn eq(&self, other: &&str) -> bool {
662 <Self as PartialEq<str>>::eq(self, other)
663 }
664}
665
666impl PartialEq<String> for Error {
667 fn eq(&self, other: &String) -> bool {
668 <Self as PartialEq<str>>::eq(self, other)
669 }
670}
671
672/// The result type for erased or message-based errors in plumbing and porcelain crates.
673///
674/// Uses [`Error`] and defaults to unit success. Public and private implementations use this alias unless
675/// callers need a concrete error type or exception-tree operations provided by [`ExnResult`] or [`ExnMessageResult`].
676/// Public APIs that already expose concrete exception types retain those types.
677pub type Result<T = ()> = std::result::Result<T, Error>;
678
679/// A result with an [`Exn<E>`](Exn) error, defaulting to unit success and an erased error type.
680///
681/// `ExnResult<T>` uses the same [`exn::Untyped`] marker as bare [`Exn`]. Specify `E` to retain a
682/// concrete error type; [`ExnMessageResult`] is the shorthand for message contexts. Use these aliases when callers
683/// need typed exceptions or exception-tree operations; other public and private code uses [`Result`].
684/// All standard result operations and [`ResultExt`] methods remain available. Use [`ResultExt::or_erased()`] for
685/// callbacks requiring erased exceptions, and `?` to propagate exceptions into [`Error`].
686/// Preserve this alias in public signatures that already expose a concrete error type.
687///
688/// ```
689/// use gix_error::{ErrorExt, ExnResult};
690///
691/// fn parse_count(input: &str) -> ExnResult<u64, std::num::ParseIntError> {
692/// input.parse::<u64>().map_err(ErrorExt::raise_typed)
693/// }
694///
695/// let error = parse_count("not a count").expect_err("the count contains letters");
696/// assert_eq!(
697/// error.error().kind(),
698/// &std::num::IntErrorKind::InvalidDigit,
699/// "callers can inspect the concrete error without downcasting"
700/// );
701/// ```
702pub type ExnResult<T = (), E = exn::Untyped> = std::result::Result<T, Exn<E>>;
703
704/// A result with a [`Message`] exception, defaulting to unit success.
705///
706/// This is [`ExnResult<T, Message>`](ExnResult). Use it when callers need direct access to the [`Message`]
707/// context or exception-tree operations. Other message-based public and private APIs use [`Result<T>`](Result).
708/// Construct it with [`ResultExt::or_raise_typed()`], [`ErrorExt::raise_typed()`], or [`bail!`].
709///
710/// ```
711/// use gix_error::{bail, ExnMessageResult};
712///
713/// fn validate(ready: bool) -> ExnMessageResult {
714/// if !ready {
715/// bail!("not ready");
716/// }
717/// Ok(())
718/// }
719///
720/// validate(true)?;
721/// assert_eq!(validate(false).expect_err("not ready").error().message, "not ready");
722/// # Ok::<(), gix_error::Error>(())
723/// ```
724pub type ExnMessageResult<T = ()> = ExnResult<T, Message>;
725
726mod test;
727pub use test::{TestError, TestResult};
728
729mod error;
730pub use error::{Class, classify};
731
732/// Various kinds of concrete errors that implement [`std::error::Error`].
733mod concrete;
734
735pub use concrete::classify::{ClassificationMarker, ResourceExhaustionKind, tag};
736pub use concrete::message::message;
737pub use concrete::metadata::{
738 Message, Metadata, MetadataValue, allocation_failure, allocation_limit, cancelled, conflict, corruption, not_found,
739 permission_denied, resource_exhaustion, retryable, unauthenticated, unsupported, validation,
740};
741
742mod location;
743pub(crate) use location::write as write_location;