Skip to main content

Crate eros

Crate eros 

Source
Expand description

§eros

github crates.io docs.rs test status no_std

Typed or untyped errors, with ergonomic propagation and no enum boilerplate. Eros lets each API specify its possible error types or use a catch-all result. Callers can handle specific error types and attach context as errors move through the call stack. Both approaches work in libraries and applications.

Choose the signature that fits your API:

ⓘ
// Propagate errors without their types.
fn load_config() -> eros::Result<Config>

// Propagate errors with their types.
fn load_config() -> eros::Result<Config, (io::Error, ParseError)>

Built on the following philosophy:

  1. Error types only matter when the caller cares about the type, otherwise this just hinders ergonomics and creates unnecessary noise. Link
  2. There should be no boilerplate needed when handling any number of errors - no need to create an error enum for each case. Link
  3. Users should be able to seamlessly transition to and from fully typed errors and handle any cases they care about. Link
  4. Errors should always provided context of the operations in the call stack that lead to the error. Link
  5. Error constructs should be performant. Link

§Philosophy In Action

§Optional Typed Errors

Error types only matter when the caller cares about the type, otherwise this just hinders ergonomics and creates unnecessary noise. Thus, it should be easy for the developer to make the type opaque for developing fast composable APIs. This is where ErrorUnion helps.

use eros::bail;

// Error type is untracked
fn validate_port(port: u16) -> eros::Result<()> {
    if port == 0 {
        bail!("Server port must be nonzero");
    }
    Ok(())
}

// Combine standard I/O and parse errors with an ad hoc validation error.
fn load_port(path: &str) -> eros::Result<u16> {
    let contents = std::fs::read_to_string(path)?;
    let port = contents.trim().parse()?;
    validate_port(port)?;
    Ok(port)
}

fn main() {
    if let Err(error) = load_port("config/port.txt") {
        println!("{error:#?}");
    }
}

§No Boilerplate

There should be no boilerplate needed when handling any number of errors (typed or untyped). This is where the magic of ErrorUnion happens.

use eros::IntoUnion;
use std::{io, num::ParseIntError};

// `ErrorUnion` is used to track each possible error type,
// instead of creating an enum for each possible error variant.
// `eros::Result<_,(..)>` is shorthand for  `Result<_,ErrorUnion<(..)>>`.
fn load_port(path: &str) -> eros::Result<u16, (io::Error, ParseIntError)> {
    let contents = std::fs::read_to_string(path).union()?;
    contents.trim().parse().union()
}

fn main() {
    if let Err(error) = load_port("config/port.txt") {
        println!("{error:#?}");
    }
}

The above code is precisely typed for what we care about and there was no need to create an error enum for each case. One can also use a type alias like type MyError = (io::Error, ParseIntError); for reuse. See the ErrorUnion section for more details how it works.

§Seamless Transitions Between Error Types

Users should be able to seamlessly transition to and from fully typed errors and handle any cases they care about.

use eros::{IntoUnion, ReshapeUnion};
use std::{io, num::ParseIntError};

fn load_port(path: &str) -> eros::Result<u16, (io::Error, ParseIntError)> {
    let contents = std::fs::read_to_string(path).union()?;
    contents.trim().parse().union()
}

// I/O Error is no longer tracked, we handled internally.
fn port_or_default(path: &str) -> Result<u16, ParseIntError> {
    load_port(path)
        .recover::<io::Error, _>(|io_error| {
            // The handler retains the error's context and backtrace.
            eprintln!("Could not read {path}: {io_error:?}; using port 8080");
            8080
        })
        // Only ParseIntError remains. We *can* extract it at the API boundary if we want.
        .map_err(|error| error.into_single())
}

fn main() {
    if let Err(error) = port_or_default("config/port.txt") {
        eprintln!("Invalid server port: {error}");
    }
}

recover removes handled error types from the result’s error set. Handle a group with .recover::<(io::Error, ParseIntError), _>(|_| 8080). Successful values and unhandled errors pass through unchanged.

For manual branching, narrow::<E, _>() extracts E and discards its diagnostics. Use narrow::<(E,), _>() or narrow::<(A, B), _>() to retain diagnostics in a smaller union. The unmatched remainder always retains its diagnostics.

Untyped APIs can still support typed recovery. For example, use a default when a configuration file is missing, while propagating permission and parse errors:

use eros::{ErrorUnion, ReshapeUnion};
use std::io;

fn load_port(path: &str) -> eros::Result<u16> {
    let contents = std::fs::read_to_string(path)?;
    Ok(contents.trim().parse()?)
}

fn port_or_default(path: &str) -> eros::Result<u16> {
    load_port(path).try_recover(|error: ErrorUnion<(io::Error,)>| {
        if error.kind() == io::ErrorKind::NotFound {
            Ok(8080)
        } else {
            Err(error.into())
        }
    })
}

The handler receives a typed error with its diagnostics. Other errors remain AnyError. You can also use narrow to select a concrete error or typed group from an untyped union or result.

Use widen to add possible error types:

use eros::{IntoUnion, ReshapeUnion};
use std::{io, net::{AddrParseError, IpAddr, TcpListener}, num::ParseIntError};

fn load_host(path: &str) -> eros::Result<IpAddr, (io::Error, AddrParseError)> {
    let contents = std::fs::read_to_string(path).union()?;
    contents.trim().parse().union()
}

fn load_port(path: &str) -> eros::Result<u16, (io::Error, ParseIntError)> {
    let contents = std::fs::read_to_string(path).union()?;
    contents.trim().parse().union()
}

fn bind_server() -> eros::Result<TcpListener, (io::Error, AddrParseError, ParseIntError)> {
    let host = load_host("config/host.txt").widen()?;
    let port = load_port("config/port.txt").widen()?;
    TcpListener::bind((host, port)).union()
}

fn main() {
    if let Err(error) = bind_server() {
        eprintln!("Could not start server: {error}");
    }
}

§Errors Have Context

Errors should always provide context of the operations in the call stack that led to the error. Users can add context with .context or .with_context. Errors also capture a Backtrace.

use eros::Context;

fn parse_port(value: &str) -> eros::Result<u16> {
    Ok(value.parse::<u16>().context("Parse server port")?)
}

fn configure_server(name: &str, port: &str) -> eros::Result<u16> {
    parse_port(port).with_context(|| format!("Configure server {name}"))
}

fn main() {
    if let Err(error) = configure_server("api", "not-a-port").context("Start application") {
        println!("{error:?}");
    }
}

With RUST_BACKTRACE=1:

invalid digit found in string

  Context (innermost first):
    1. Parse server port
    2. Configure server api
    3. Start application

Backtrace (captured):
[3 frames hidden for brevity]
   3: example::parse_port
             at ./src/main.rs:4:29
   4: example::configure_server
             at ./src/main.rs:8:5
   5: example::main
             at ./src/main.rs:12:25
[17 frames hidden for brevity]
§Location

The location feature flag adds a location at compile time for error creation and each context. This can be used with or in place of backtrace, as it is lighter than a full backtrace and can be used in wasm environments (backtraces do not work in wasm environments) and no_std environments.

§Optimizations

Eros comes with the context and backtrace feature flags enabled by default. Disabling them removes backtrace and context tracking from ErrorUnion<T>, and all context methods become a no-op. Thus, it may be optimized away by the compiler.

ErrorUnion’s stack size is pointer size (uses a Box). Boxing errors is a common trick to increase performance and decrease stack memory usage in many cases. This is because boxing may decrease the size of the return type, e.g. Result<(),Box<u128>> is smaller than Result<(),u128>>.

See the Use In Libraries section as well.

§ErrorUnion

§Open Sum Type

ErrorUnion is an open sum type. An open sum type takes full advantage of rust’s powerful type system. It differs from an enum in that you do not need to define any actual new type in order to hold some specific combination of variants, but rather you simply describe the ErrorUnion as holding one value out of several specific possibilities. This is declared by using a tuple of those possible variants as the generic parameter for the ErrorUnion.

For example, a ErrorUnion<(io::Error, fmt::Error)> contains either a io::Error or a fmt::Error. The benefit of this over creating specific enums for each function becomes apparent in larger codebases where error handling needs to occur in different places for different errors. As such, ErrorUnion allows you to quickly specify a function’s return value as involving a precise subset of errors that the caller can clearly reason about. This Provides maximum composability with no boilerplate. E.g.

use eros::ErrorUnion;
use std::{fmt, io};

fn main() {
    let error: ErrorUnion<MyError>;
    let result: eros::Result<(), MyError>;
}

type MyError = (fmt::Error, io::Error); // A type alias can be used to make statements more concise

vs

use std::{fmt, io};

fn main() {
    let error: MyError;
    let result: Result<(), MyError>;
}

#[derive(Debug)]
pub enum MyError {
    FmtError(fmt::Error),
    IoError(io::Error),
}

impl std::fmt::Display for MyError {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MyError::FmtError(e) => write!(fmt, "{}", e),
            MyError::IoError(e) => write!(fmt, "{}", e),
        }
    }
}

impl std::error::Error for MyError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            MyError::FmtError(e) => e.source(),
            MyError::IoError(e) => e.source(),
        }
    }
}

impl From<fmt::Error> for MyError {
    fn from(error: fmt::Error) -> Self {
        MyError::FmtError(error)
    }
}

impl From<io::Error> for MyError {
    fn from(error: io::Error) -> Self {
        MyError::IoError(error)
    }
}

Additionally, the complexity of the second option grows exponentially the more error enums have to be combined from different functions. That is why a lot of crates opt for not precisely defining errors for APIs and instead choose a single error enum or struct for the entire crate. See the Why Traditional Enum Errors Scale Poorly section for a deeper dive into this.

When the error union should encompass the full set of possible errors, use AnyError:

eros::Result<()> is shorthand for eros::Result<(), AnyError>, which in turn is shorthand for Result<(), ErrorUnion<AnyError>>.

§Tracing

ErrorUnion also allows adding context to an error throughout the callstack with the context or with_context methods. This context may be information such as variable values or ongoing operations while the error occurred. If the error is handled higher in the stack, then this can be disregarded (no log pollution). Otherwise you can log it (or panic), capturing all the relevant information in one log. A backtrace is captured and included with the error when RUST_BACKTRACE is set.

§Context Macro

For some functions, one may want to attach the same context to every error that can be returned from that function. Writing .with_context(...) on each fallible call quickly becomes repetitive and can obscure the intent of the function. For example:

use eros::Context;

fn load_port(path: &str) -> eros::Result<u16> {
    let contents = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to load server port from {}", path))?;
    let port = contents.trim().parse::<u16>()
        .with_context(|| format!("Failed to load server port from {}", path))?;
    Ok(port)
}

fn main() {
    if let Err(error) = load_port("config/port.txt") {
        println!("{error:#?}");
    }
}

To help with this, eros provides the context attribute macro. The macro wraps the function and automatically adds the supplied context to any error returned from it:

use eros::{Context, context};

// Use #[eager_context(...)] to format owned parameters before the body runs, even on success.
#[context("Failed to load server port from {}", path)]
fn load_port(path: &str) -> eros::Result<u16> {
    let contents = std::fs::read_to_string(path)?;
    let port = contents.trim().parse::<u16>()?;
    Ok(port)
}

fn main() {
    if let Err(error) = load_port("config/port.txt") {
        println!("{error:#?}");
    }
}

Whether reading the file or parsing its contents fails, the error includes Failed to load server port from config/port.txt alongside the original I/O or parse error. The macro attaches this context once, while keeping the function body focused on the actual logic.

§Automatic Context from Parameters

When the context simply consists of “which arguments was this function called with?”, the format string can often be inferred automatically.

Instead of providing an explicit format string, use #[context] and annotate the parameters that should appear in the generated context with #[fmt(...)] where ... is the desired formatting:

use eros::{context, Context};

#[derive(Debug)]
struct Flags {
    enabled: bool,
}

fn result() -> eros::Result<()> {
    eros::bail!("This is an error")
}

#[context]
fn process(
    #[fmt("{}")] name: &str,
    count: usize,
    #[fmt("{:?}")] flags: &Flags,
) -> eros::Result<()> {
    result()?;
    result()?;
    Ok(())
}

fn main() {
    process(
        "example",
        42,
        &Flags { enabled: true },
    );
}

The generated context is equivalent to:

ⓘ
format!(
    "name: {}\nflags: {:?}\n",
    name,
    flags,
)

Only annotated parameters are included in the generated context. Parameters without #[fmt(...)] are ignored, allowing sensitive values or uninteresting arguments to be omitted.

§Best Practices

§Use In Libraries

eros’s flexibility and optimizations make it the perfect option for both libraries and binaries.

Libraries should consider setting default-features = false on their eros dependency and allowing downstream crates to enable the features they need. The library can enable these features for its own tests.

§Public APIs
§Approach A: Exposing ErrorUnion in Public APIs

Exposing ErrorUnion in a public API is sometimes preferred, especially if crates are internal. It allows multiple crates to use the power of these constructs together.

Before choosing this approach ask “Will a downstream care about differentiating between these types?” e.g. exposing a io::Error may or may not be useful. In fact, it may be more useful for a downstream to expose a type specific to the crate e.g. CrateError. One could then expose an e.g.ErrorUnion<(CrateError,)>. But if it is desired to remove ErrorUnion altogether, approach B dives deeper into this.

§Approach B: Replacing ErrorUnion With Concrete Crate Errors

If one wants to add a custom error type for public APIs without exposing constructs like ErrorUnion, use the into_inner() method at these boundaries. This is a common pattern, since most crates already define their own error type for public-facing APIs.

Example Implementation
use std::io;

use eros::{ErrorUnion, SendSyncError, TypeSet, bail};

#[derive(Debug)]
struct CrateError(Box<dyn SendSyncError>);

impl std::fmt::Display for CrateError {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(fmt, "CrateError: {}", self.0)
    }
}

impl std::error::Error for CrateError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(self.0.as_ref())
    }
}

impl<T: TypeSet> From<ErrorUnion<T>> for CrateError {
    fn from(e: ErrorUnion<T>) -> Self {
        CrateError(e.into_inner())
    }
}

fn internal_api() -> eros::Result<()> {
    bail!(io::Error::new(io::ErrorKind::Other, "io error"))
}

pub fn public_api() -> Result<(), CrateError> {
    internal_api().map_err(Into::into)
}

This way the library can still use ErrorUnion internally for function composition, enabling features like context and backtrace for its own tests, while downstream crates only ever see a single concrete error type. CrateError is effectively just a newtype wrapper around a boxed error, so the conversion at the boundary stays cheap regardless of how many error variants the library handles internally. When no crate enables context, backtrace, or location, converting an internal ErrorUnion into a library’s boxed error via into_inner() reuses the existing allocation (no-op) so there is no cost to use eros in a library for any downstreams.

This pattern works for AnyError as shown above, but it isn’t limited to it. When the internal ErrorUnion uses a typed tuple instead, into_enum can be used to convert into an enum, which can then be mapped into the crate’s own error enum — giving callers something they can exhaustively match on.

Example Implementation
use eros::{E2, ErrorUnion, IntoUnion};
use std::{fmt, io};

#[derive(Debug)]
pub enum CrateError {
    Io(io::Error),
    Format(fmt::Error),
}

impl std::fmt::Display for CrateError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CrateError::Io(e) => write!(f, "{}", e),
            CrateError::Format(e) => write!(f, "{}", e),
        }
    }
}

impl std::error::Error for CrateError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            CrateError::Io(e) => e.source(),
            CrateError::Format(e) => e.source(),
        }
    }
}

impl From<ErrorUnion<(io::Error, fmt::Error)>> for CrateError {
    fn from(error: ErrorUnion<(io::Error, fmt::Error)>) -> Self {
        // `into_enum` converts the `ErrorUnion` into `E2<io::Error, fmt::Error>`,
        match error.into_enum() {
            E2::A(e) => CrateError::Io(e),
            E2::B(e) => CrateError::Format(e),
        }
    }
}

fn regular_typed_result1() -> Result<(), io::Error> {
    Err(io::Error::new(io::ErrorKind::AddrInUse, "message here"))
}

fn regular_typed_result2() -> Result<(), fmt::Error> {
    Err(fmt::Error)
}

fn internal_api() -> eros::Result<(), (io::Error, fmt::Error)> {
    regular_typed_result1().union()?;
    regular_typed_result2().union()?;
    Ok(())
}

pub fn public_api() -> Result<(), CrateError> {
    internal_api().map_err(Into::into)
}

fn main() {
    match public_api() {
        Ok(()) => println!("Success!"),
        Err(CrateError::Io(e)) => println!("IO error: {}", e),
        Err(CrateError::Format(e)) => println!("Format error: {}", e),
    }
}

With this, internal composing of errors can remain precise and ergonomic vs traditional enums, as outlined in Why Traditional Enum Errors Scale Poorly section. And downstream users are not exposed to the ErrorUnion type and instead see a traditional error enum. Note even if typed tuples are used internally, it is still completely valid to choose to type erase at the boundary with into_inner.

§Context Placement: Two Approaches

There are two reasonable philosophies for where in the call stack context should be attached. Eros is flexible enough to support either, but it’s worth picking one and being consistent within a codebase.

§Approach 1: Attach Context at the Function

Under this approach, a function attaches context describing itself and its own parameters via #[context]. The function “owns” its own description, so every caller gets the same context for free, with no risk of forgetting it or duplicating it slightly differently at each call-site.

use eros::{Context, context};

#[context("Failed to do some action. param was {}", param)]
fn do_some_action(param: &str) -> eros::Result<()> {
    eros::bail!("This is an error")
}

fn func1() -> eros::Result<()> {
    let param = "xyz";
    do_some_action(param)
}

fn func2() -> eros::Result<()> {
    let param = "abc";
    do_some_action(param)
}

fn main() {
    func1();
    func2();
}

Why: it removes ambiguity about whose job it is to attach context. If every function attaches context describing its own operation and inputs, nothing needs to be re-derived or duplicated by callers, and nothing is silently dropped because every caller assumed some other layer would handle it.

Tradeoff: if a function’s parameter is itself just forwarded from its caller (and that caller already attaches it too), the same value can appear in context more than once as the error bubbles up. Note if the context feature is disabled with_context becomes a no-op, so the cost is avoidable.

§Approach 2: Attach Context Only at the Boundary Where Information Would Otherwise Be Lost

A function should only attach context that the caller doesn’t already have. If a caller already knows the value of param, then a callee re-stating param in its own context adds no new information, just noise.

Responsibility for attaching a given piece of context passes transitively up the stack to whichever function is the last one that still has access to the information, even if that’s several layers above where the error actually originated. In the example below, func2 attaches nothing — it leaves that to its callers — and the context only gets attached at func1 and func1b, the two places where param would otherwise be lost:

use eros::Context;

fn do_some_action(param: &str) -> eros::Result<()> {
    eros::bail!("This is an error")
}

fn func2(param: &str) -> eros::Result<()> {
    do_some_action(param)
}

fn func1() -> eros::Result<()> {
    let param = "xyz";
    func2(param).with_context(|| format!("Failed to do some action. param was {}", param))
}

fn func1b() -> eros::Result<()> {
    let param = "abc";
    func2(param).with_context(|| format!("Some action failed with param {}", param))
}

Why: it keeps individual error messages lean, avoids restating the same value at every layer, and sidesteps the classic connection failed: connection failed: connection failed: no route to host style of redundant, nested context.

Tradeoff: because no single function is locally responsible for attaching a given piece of context, it takes discipline and more time has to be spent at each call-site — you have to ask “would this information otherwise be lost going up the stack from here?” If a function is called from many places, that question has to be answered (and the same context written) at each call-site rather than once at the function’s own definition. It’s also easy to accidentally end up restating context slightly differently at two call-sites — in the example above, func1 and func1b phrase the same underlying fact as "Failed to do some action. param was {}" and "Some action failed with param {}" — since nothing enforces a single canonical phrasing the way #[context] on the function itself does. It is also easy to get lazy and skip attaching context altogether at a given call-site, silently losing information that would have been captured automatically under Approach 1.

§Backtrace vs Location

eros has two location tracking feature flags backtrace, which captures a backtrace at error creation if RUST_BACKTRACE env variable is set, and location, which captures the location in the code that the error and context were created from. location is more efficient than backtrace since the call location is injected at compile time. While backtrace is generally more precise and useful. Both of these can be used together. location becomes especially useful for wasm or no_std environments where backtraces are not supported. location is not enabled by default, while backtrace is.

§Logging

For ErrorUnion, Display prints the root error followed by its Error::source() chain. Debug produces a human-readable report with context, locations, and backtrace information.

FormatOutputTracing field
{}Root and sources separated by <-error = %error
{:#}Root onlyerror = %format_args!("{error:#}")
{:?}Root, sources, contexts, locations, and backtraceerror = ?error
{:#?}Same report without locations and backtraceerror = %format_args!("{error:#?}")

For logging, err_trail is recommended. Libraries can use its constructs like error!, warn!, info!, debug!, and trace! macros while downstream applications select the tracing, log, or defmt backend. If no backend is selected by a downstream, then the code is optimized away by the compiler.

The ErrContext trait in err_trail also provides methods like .warn(()), which logs an Err using Display and returns the result unchanged:

ⓘ
use eros::bail;
use err_trail::ErrContext;

fn eros_result() -> eros::Result<()> {
    bail!("Something went wrong")
}

fn main() {
    tracing_subscriber::fmt()
        .without_time()
        .with_target(false)
        .with_ansi(false)
        .init();

    if let Err(error) = eros_result() {
        err_trail::error!(error = %error, "Operation failed");
    }

    let _result = eros_result().warn(());
}

The error! call emits:

ERROR Operation failed error=Something went wrong

The .warn(()) call emits:

WARN Something went wrong

§Additional Features

§Better Backtrace

Other backtrace examples in this README use [N frames hidden for brevity] to mark frames omitted from the documentation. The default output still includes those frames. Enable better_backtrace to filter recognized dependency and runtime frames automatically.

§Adding Source Chains

Use map_inner to change the main error while keeping the original failure as its source. The closure receives the boxed inner error; return an error that stores it and exposes it through Error::source():

use eros::SendSyncError;
use std::{error::Error, fmt};

#[derive(Debug)]
struct UpdateError {
    source: Box<dyn SendSyncError>,
}

impl fmt::Display for UpdateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Update preparation failed")
    }
}

impl Error for UpdateError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(self.source.as_ref())
    }
}

let error = eros::error!("TLS certificate has expired")
    .map_inner(|source| UpdateError { source });

println!("{error}");
Update preparation failed <- TLS certificate has expired

For a union with a single possible error type, map_single passes the concrete error to the closure and preserves context, location, and backtrace. Or use into_single to extract that error and discard the metadata.

§Diagnostic Logging

The optional diagnostic feature adds .to_display_json() and .to_debug_json(), returning the same information as ordinary Display and Debug in a serde_json::Value. Display diagnostics contain root and sources; Debug diagnostics add contexts, optional location objects, and backtrace with status and text.

ⓘ
// ConfigError displays "cannot open configuration"; StartupError displays "startup failed".
// Both expose their boxed `source` through Error::source().

let error = eros::error!("permission denied")
    .map_inner(|source| ConfigError { source })
    .context("read /etc/app.toml")
    .context("start service");

tracing::error!(error = %error, "startup failed");
tracing::error!(error = ?error, "startup failed");
println!("to_display_json: {}", error.to_display_json());
println!("to_debug_json: {}", error.to_debug_json());

// Wrap again, preserving the full source chain.
let error = error.map_inner(|source| StartupError { source });
println!("replacement: {error}");

With default Eros features, diagnostic, RUST_LIB_BACKTRACE=0, and a text subscriber configured without timestamps, targets, or ANSI colors, the output is:

ERROR startup failed error=cannot open configuration <- permission denied
ERROR startup failed error=cannot open configuration
  caused by: permission denied

  Context (innermost first):
    1. read /etc/app.toml
    2. start service

Backtrace (disabled):
to_display_json: {"root":"cannot open configuration","sources":["permission denied"]}
to_debug_json: {"backtrace":{"status":"disabled","text":null},"contexts":[{"message":"read /etc/app.toml","user_facing":false},{"message":"start service","user_facing":false}],"root":"cannot open configuration","sources":["permission denied"]}
replacement: startup failed <- cannot open configuration <- permission denied

§Exposing Errors To Application Users

Not every error message should be shown directly to end users of an application.

Operational details such as SQL queries, filesystem paths, internal identifiers, etc. often make poor user experiences and may even leak sensitive information. Conversely, some errors are intentionally designed to be presented directly to users.

Instead, construct a user-facing message from two sources:

  1. User context attached throughout the call stack. Enabled through the user_context feature flag
  2. The underlying error itself, if the application recognizes it as safe to display.
Example Implementation
ⓘ
use eros::{Context, ErrorUnion, IntoAnyUnion, SendSyncError, TypeSet};

#[derive(Debug)]
struct SystemDiskError;

impl std::fmt::Display for SystemDiskError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Critical IO failure at block 0x7FA3")
    }
}

impl std::error::Error for SystemDiskError {}

#[derive(Debug)]
struct InvalidPasswordError;

impl std::fmt::Display for InvalidPasswordError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Your password must be at least 8 characters long.")
    }
}

impl std::error::Error for InvalidPasswordError {}

// Add valid errors to display to the user here
fn root_error_message(error: &dyn SendSyncError) -> String {
    if let Some(error) = error.as_any().downcast_ref::<InvalidPasswordError>() {
        error.to_string()
    } else {
        "An internal error occurred.".to_owned()
    }
}

fn build_user_error_message<E>(error: &ErrorUnion<E>) -> String
where
    E: TypeSet,
{
    let mut message = String::new();
    let error_message = root_error_message(error.inner());
    message.push_str(&error_message);

    for frame in error.contexts().filter(|frame| frame.is_user_facing()) {
        message.push('\n');
        message.push_str(&frame.to_string());
    }

    message
}

fn validate_password(password: &str) -> eros::Result<()> {
    if password.len() < 8 {
        return Err(InvalidPasswordError)
            .context("Password validation failed")
            // This context is marked as "user facing" meaning it is safe to expose to the user
            .user_context("Please choose a stronger password.")
            .any_union();
    }
    Ok(())
}
fn load_configuration() -> eros::Result<()> {
    Err(SystemDiskError)
        .context("Failed to read configuration from /etc/my-app/config.toml")
        .any_union()
}
#[test]
fn main() {
    let password_error = validate_password("123").unwrap_err();
    println!("User message:");
    println!("{}", build_user_error_message(&password_error));
    let system_error = load_configuration().unwrap_err();
    println!("\nUser message:");
    println!("{}", build_user_error_message(&system_error));
}
User Message:
Your password must be at least 8 characters long.
Please choose a stronger password.
User Message:
An internal error occurred.

This approach keeps internal diagnostics while making the user-facing experience explicit. Applications remain free to decide which information is safe to expose, while ErrorUnion continues to focus on error composition, tracing, and context propagation.

§Anyhow

eros comes with an anyhow feature flag. This adds a ErrorUnion::from_anyhow function for converting an anyhow::Error to an ErrorUnion. This can help integrate with legacy code.

eros can also quickly replace anyhow in any crate as simple as replacing all occurrences of:

  • anyhow! with error!
  • anyhow::Error with eros::ErrorUnion
  • anyhow:: with eros::

anyhow and eros give context different roles. In anyhow, each .context(...) call adds an outer layer to the error chain. The latest context becomes the main message, while earlier contexts and the original error remain as causes. As an error travels through its callers, this presents the outermost operation first.

ⓘ
let error = anyhow::anyhow!("TLS certificate has expired")
    .context("fetch https://updates.example.com/manifest.json")
    .context("prepare application update to v2.4.0");

println!("{error:?}"); // Debug shows the main message and its causes.
prepare application update to v2.4.0

Caused by:
    0: fetch https://updates.example.com/manifest.json
    1: TLS certificate has expired

eros keeps the original error as the main message and presents context separately, in the order it was added. As the error travels up the call stack, context follows stack trace order: nearest the failure first, then outward through its callers:

ⓘ
let error = eros::error!("TLS certificate has expired")
    .context("fetch https://updates.example.com/manifest.json")
    .context("prepare application update to v2.4.0");

println!("{error:#?}"); // Alternate Debug omits locations and the backtrace.

With the context feature enabled (the default):

TLS certificate has expired

  Context (innermost first):
    1. fetch https://updates.example.com/manifest.json
    2. prepare application update to v2.4.0

The headline identifies the problem immediately: an expired certificate. The context then identifies the request and the application operation that encountered it.

§Why Traditional Enum Errors Scale Poorly

Traditional enum-based error handling breaks down as soon as you compose functions, because each new layer of composition demands its own enum.

§The Problem

Suppose three low-level functions each return a precise error enum:

use std::io;
use std::num::ParseIntError;
use std::net::AddrParseError;

#[derive(Debug)]
pub enum ReadError {
    Io(io::Error),
    Format(String),
}
fn read_file() -> Result<String, ReadError> { todo!() }

#[derive(Debug)]
pub enum ParseError {
    InvalidInt(ParseIntError),
    MissingKey(String),
}
fn parse_config(_data: &str) -> Result<u16, ParseError> { todo!() }

#[derive(Debug)]
pub enum NetworkError {
    BadAddr(AddrParseError),
    Io(io::Error),
}
fn open_socket(_port: u16) -> Result<(), NetworkError> { todo!() }

To chain them in initialize_system, a precise return type requires a fourth enum wrapping the other three — plus a From impl for each, just to make ? work:

ⓘ
#[derive(Debug)]
pub enum InitError {
    Read(ReadError),
    Parse(ParseError),
    Net(NetworkError),
}

impl From<ReadError> for InitError {
    fn from(e: ReadError) -> Self { InitError::Read(e) }
}
impl From<ParseError> for InitError {
    fn from(e: ParseError) -> Self { InitError::Parse(e) }
}
impl From<NetworkError> for InitError {
    fn from(e: NetworkError) -> Self { InitError::Net(e) }
}

fn initialize_system() -> Result<(), InitError> {
    let data = read_file()?;
    let port = parse_config(&data)?;
    open_socket(port)?;
    Ok(())
}

Note that io::Error is now buried two levels deep in two different places (InitError::Read(ReadError::Io(_)) and InitError::Net(NetworkError::Io(_))), so callers who just want to handle IO errors have to match both paths:

ⓘ
match initialize_system() {
    Ok(()) => println!("Success!"),
    Err(InitError::Read(ReadError::Io(_))) => { /* handle */ }
    Err(InitError::Net(NetworkError::Io(_))) => { /* handle */ }
    Err(other) => println!("Some other error occurred: {:?}", other),
}

Add a fourth step that returns a DatabaseError and the cycle repeats: a new enum, new From impls, and every downstream match needs updating.

§Why Crates Give Up

Faced with this growth, most crates abandon precision entirely and adopt one monolithic, crate-wide error enum:

ⓘ
#[derive(Debug, thiserror::Error)]
pub enum CrateError {
    #[error("IO error: {0}")]
    Io(#[from] io::Error),
    #[error("Parse error: {0}")]
    Parse(#[from] ParseIntError),
    #[error("Network error: {0}")]
    Network(#[from] AddrParseError),
    #[error("Custom error: {0}")]
    General(String),
}

This kills the boilerplate, but it also kills accuracy: every function now claims it can return any crate error, even when most are impossible for that particular call path. parse_config’s caller has to account for a NetworkError that can never actually occur.

§How ErrorUnion Avoids This

ErrorUnion sidesteps the dilemma entirely. No new enum is needed to combine errors, so precision and ergonomics stop being a trade-off.

ⓘ
type MyError = (io::Error, ParseIntError, AddrParseError);

fn initialize_system() -> eros::Result<(), MyError> {
    let data = read_file().union()?;
    let port = parse_config(&data).union()?;
    open_socket(port).union()?;
    Ok(())
}

The signature stays exact — only the errors that can actually occur are listed — and adding a fourth fallible step just means adding one type to the tuple, not a new enum and a new set of From impls, or a rewritten match.

§no_std

This crate supports #![no_std], but requires alloc.

Default features also must be disabled and a global allocator available. The backtrace feature does not work with no std, but backtrace can be replaced with the location feature which does.

§Special Thanks

Special thank you to the authors and contributors of the following crates that inspired eros:

Re-exports§

pub use type_set::E1;
pub use type_set::E2;
pub use type_set::E3;
pub use type_set::E4;
pub use type_set::E5;
pub use type_set::E6;
pub use type_set::E7;
pub use type_set::E8;
pub use type_set::E9;
pub use type_set::E10;
pub use type_set::E11;
pub use type_set::E12;
pub use type_set::E13;
pub use type_set::E14;
pub use type_set::E15;
pub use type_set::E16;
pub use type_set::E17;
pub use type_set::E18;
pub use type_set::E19;
pub use type_set::E20;
pub use type_set::E21;
pub use type_set::E22;
pub use type_set::E23;
pub use type_set::E24;
pub use type_set::E25;
pub use type_set::E26;
pub use type_set::TypeSet;

Modules§

prelude
Extension traits for converting results, reshaping error sets, and adding context.
type_set

Macros§

bail
Returns early with an ErrorUnion wrapped in Err.
ensure
Returns an ErrorUnion error if the condition is false.
error
Creates an ErrorUnion from a message or error.

Structs§

AbsentValueError
An Error type for unwrapping an Option that is None, but expected to be Some. This is used when it is desired to propagate this information rather than immediately panic with .expect(..) - presumably to capture additional context up the call stack. This is created by calling .context(..) on an Option<T> that was None. Thus constructing this type is always paired with information to further explain why the value should exist or provided additional context around the operation.
ContextFrame
An attached context value and its captured metadata.
ContextValue
A context value containing a message or an error.
ErrorUnion
ErrorUnion is an open sum type of errors. It differs from an enum in that you do not need to define any actual new type in order to hold some specific combination of variants, but rather you simply describe the ErrorUnion as holding one value out of several specific possibilities, defined by using a tuple of those possible variants as the generic parameter for the ErrorUnion. Every tuple member must implement SendSyncError.
MsgError
An error containing a message.
StdError
An ErrorUnion adapter implementing core::error::Error.

Enums§

AnyError
A marker type for ErrorUnion representing all possible errors

Traits§

Context
Provides context methods to add context to Result.
IntoAnyUnion
IntoUnion
ReshapeUnion
Reshapes error sets and handles specific error types directly on results.
SendSyncError
Any error that satisfies this trait’s bounds can be used in a ErrorUnion

Type Aliases§

Result

Attribute Macros§

context
Automatically wraps a function body with eros context.
eager_context
Like [context], but formats before the body runs (including success) when context is enabled.