Skip to main content

Error handling

CGP gives each context one shared abstract error type and lets it select providers for raising and wrapping errors. Generic code can then report failures without choosing the application’s concrete error representation.

The application chooses the concrete error type when it assembles the context. A generic provider may encounter a parse error, an io::Error, or a string without knowing whether the application uses anyhow::Error or another type.

CGP separates that choice from error construction through cooperating components. HasErrorType defines the shared Self::Error, CanRaiseError<SourceError> converts a source error into it, and CanWrapError<Detail> attaches detail to an existing error. The context selects the type and behavior through wiring.

Import wiring keys and error providers explicitly when configuring error handling. The prelude supplies HasErrorType, CanRaiseError, and CanWrapError, but the component markers live under cgp::core::error and the generic error providers under cgp::extra::error. For example, import cgp::core::error::ErrorRaiserComponent and cgp::extra::error::RaiseFrom when wiring RaiseFrom.

HasErrorType: the shared abstract error​

HasErrorType defines the shared Error type used by a context’s fallible operations. It is declared with #[cgp_type] and behaves like other abstract types: the context selects its associated type through wiring or a direct impl.

#[cgp_type]
pub trait HasErrorType {
type Error: Debug;
}

pub type ErrorOf<Context> = <Context as HasErrorType>::Error;

The concrete error type must implement Debug. This supports .unwrap() and debug logging without an additional bound. ErrorOf<Context> abbreviates the associated-type path, so generic code can return Result<T, Self::Error> or Result<T, ErrorOf<Context>> without naming the concrete error. cgp::core::error::ErrorOnly<E> is a zero-sized, Default context whose only trait is HasErrorType with Error = E; use ErrorOnly::<String>::default() where a test needs a context with an error type and nothing else.

A shared error type lets fallible operations compose within a context. Each fallible trait depends on HasErrorType instead of declaring an independent associated error type that callers would have to reconcile. HasErrorType defines only the type; the raising and wrapping components define behavior.

Prefer #[use_type(HasErrorType.Error)] when declaring a fallible component. It adds the supertrait and rewrites bare Error to <Self as HasErrorType>::Error, avoiding a handwritten supertrait bound and repeated Self::Error paths.

Wire ErrorTypeProviderComponent to UseType<E> to select the concrete error. The blanket impl generated by #[cgp_type] supplies the type, as it does for other abstract-type components:

#[cgp_component(Validator)]
#[use_type(HasErrorType.Error)]
pub trait CanValidate {
fn validate(&self) -> Result<(), Error>;
}

pub struct App;

delegate_components! {
App {
ErrorTypeProviderComponent: UseType<String>,
}
}

The example imports the shared Error into CanValidate and selects String for App. The standalone backends cgp-error-anyhow, cgp-error-eyre, and cgp-error-std provide error-type providers for their respective libraries; see error backends. A context can also choose the type directly with impl HasErrorType for App { type Error = String; }.

CanRaiseError and CanWrapError: producing and enriching the error​

CanRaiseError<SourceError> converts a concrete source error into the context’s abstract error. CanWrapError<Detail> adds detail to an existing abstract error. Both import Error with #[use_type(HasErrorType.Error)] and can select a different provider for each source or detail type:

#[cgp_component(ErrorRaiser)]
#[derive_delegate(UseDelegate<SourceError>)]
#[use_type(HasErrorType.Error)]
pub trait CanRaiseError<SourceError> {
#[track_caller]
fn raise_error(error: SourceError) -> Error;
}

#[cgp_component(ErrorWrapper)]
#[derive_delegate(UseDelegate<Detail>)]
#[use_type(HasErrorType.Error)]
pub trait CanWrapError<Detail> {
#[track_caller]
fn wrap_error(error: Error, detail: Detail) -> Error;
}

Both methods are associated functions, so generic code can call them without a context value. Both are also #[track_caller], which Rust applies to every impl of them, including the forwarding impls CGP generates. An error library that records Location::caller(), such as eyre, therefore sees the line that called raise_error. The location survives only while every call on the way to the library is #[track_caller]: Into::into and eyre's constructors are, but a helper function the provider calls needs the attribute too. Context::raise_error(source) takes a source error by value and returns the abstract error. Context::wrap_error(err, detail) takes an existing error and returns it with added detail.

The component attributes name the provider traits ErrorRaiser and ErrorWrapper. The library definitions shown above use #[derive_delegate(UseDelegate<...>)] to support dispatch by SourceError or Detail. The wiring examples below use the preferred open form.

A provider can require the raising and wrapping traits without naming a concrete context or error type:

#[cgp_component(Loader)]
#[use_type(HasErrorType.Error)]
pub trait CanLoad {
fn load(&self, path: &str) -> Result<String, Error>;
}

#[cgp_impl(new LoadOrFail)]
#[uses(CanRaiseError<String>, CanWrapError<String>)]
#[use_type(HasErrorType.Error)]
impl Loader {
fn load(&self, path: &str) -> Result<String, Error> {
if path.is_empty() {
let err = Self::raise_error("empty path".to_owned());
return Err(Self::wrap_error(err, format!("while loading {path}")));
}
Ok(format!("contents of {path}"))
}
}

LoadOrFail requires CanRaiseError<String> to create an error from a message and CanWrapError<String> to add detail. These impl-side dependencies are satisfied by the context’s providers. Wiring determines the concrete error returned by load.

Wiring the behavior: generic error providers​

Wire ErrorRaiserComponent and ErrorWrapperComponent to select how a context creates and enriches errors. The cgp-error-extra crate supplies zero-sized providers that work across error types, while standalone backends support specific libraries such as anyhow. A context can combine a backend’s concrete error type with generic raising and wrapping strategies. The generic providers are listed below; the backends' own providers and how to route source types to them are in error backends.

Choose among these providers according to the operation and required bounds:

  • RaiseFrom: Raises a source E through From when Context::Error: From<E>. Prefer it when the concrete error already supports that conversion.
  • ReturnError: Returns the source unchanged when it is already the context's error type (HasErrorType<Error = E>).
  • RaiseInfallible: Handles core::convert::Infallible with an unreachable empty match. It lets generic fallible code use an operation that cannot fail.
  • PanicOnError: Panics with the source's Debug output. Use it when the context treats errors as immediate failures, such as in tests.
  • DiscardDetail: Implements wrapping by returning the error unchanged and dropping the detail. Use it when the error type cannot carry extra context.
  • DebugError and DisplayError: Implement raising and wrapping by formatting a source or detail into String, then forwarding to the context's string handler. They use Debug and Display/to_string() respectively and require the crate's alloc feature.

Use a single RaiseFrom entry when the abstract error implements From for every source the context needs to raise:

delegate_components! {
App {
ErrorRaiserComponent: RaiseFrom,
}
}

Wire a string handler alongside DebugError or DisplayError. These providers format a source error or detail as a String, then forward it through the context’s CanRaiseError<String> or CanWrapError<String> implementation. They do not choose the concrete error type. Never wire the String key itself to either of them: the provider would forward the formatted string to itself, and the check fails with E0275 (overflow evaluating DebugError: ErrorRaiser<App, String>). Give String a provider that finishes the job, such as RaiseFrom.

Use open to select a provider per source type. This example sends strings directly to RaiseFrom and parse errors through DebugError first:

delegate_components! {
App {
open ErrorRaiserComponent;

@ErrorRaiserComponent.String: RaiseFrom,
@ErrorRaiserComponent.ParseError: DebugError,
}
}

open ErrorRaiserComponent; enables per-type entries in the context’s table. Each @ErrorRaiserComponent.<SourceError>: Provider entry selects a provider for one source type. The generated RedirectLookup impl supports this dispatch without an additional #[derive_delegate] attribute.

Legacy wiring puts the same entries in a nested UseDelegate<new AppErrorRaisers { String: RaiseFrom, ParseError: DebugError }> table. That form remains common but is slated for deprecation. Prefer open for new wiring; see wiring for both forms.

The example routes both source types to the same abstract error. RaiseFrom converts strings directly, while DebugError formats a ParseError and forwards the result through the string entry. Each provider choice determines which sources the context accepts and how they are represented. Verify the wiring with check_components!.

Error handling combines abstract types, components, and wiring. HasErrorType selects the shared type through UseType<E> or a backend provider. CanRaiseError and CanWrapError require that type and dispatch by source or detail type through open or legacy UseDelegate tables. Error backends covers the concrete backends.

Consult the online knowledge base for the component and provider definitions: