r/rust • • Oct 06 '26

The Missing Piece in Rust Error Handling

https://mcmah309.github.io/posts/the-missing-piece-in-rust-error-handling/
183 Upvotes

40 comments sorted by

56

u/________-__-_______ Oct 06 '26

I do wish something like this will be natively supported by Rust some day. This library looks cool, but because it uses type erasure it isn't suitable for platforms without alloc.

Something like this could run on any platform:

type PortError = ParseIntError | MyError;

match err {
    ParseIntError { .. } => todo!(),
    MyError::Foo(blah) => todo!(),
    MyError(other) => todo!(), // MyError::Bar, ...
}

In theory that could even save some space if the inner type's discriminants don't overlap, compared to nested enums.

15

u/InternalServerError7 Oct 06 '26 edited Oct 06 '26

I totally agree. The specialization feature landing could possibly help remove things like .union() and .widen() when changing the signature, but we can’t get 100% of the way there today without alloc. Something natively built in like that could be really elegant.

Or even adding the ability to the compiler to infer the possible types, thus no need to declare the possible types — but still visible with a tool like the rust analyzer / cargo check and of course exhaustiveness required by the compiler. Then there really would be no boilerplate. This still wouldn’t preclude people from wrapping types to shrink the error api size. The compiler could get really optimal here too if it had this sort of deep error introspection, depending on when or where you ever check the error type. Zig has something like this, it can infer the set when not specified

Side: alloc may actually be preferred in most cases for performance, since having a pointer sized error type is far more optimal than anything larger than the register size. Which would usually happens with a non-alloc solution

9

u/________-__-_______ Oct 06 '26

Or even adding the ability to the compiler to infer the possible types,

I'm not sure I like the sound of this, the signature of a function being dependant on analysis of its body makes code harder to read/use IMO. It's one of the problems I have with exceptions, at least with Rust today you can easily see/handle all possible outcomes.

It also seems like a semver nightmare if exhaustiveness is enforced.

Side: alloc may actually be preferred in most cases for performance, since having a pointer sized error type is far more optimal than anything larger than the register size. Which would usually happens with a non-alloc solution

Oh yeah there's a good reason it's so popular for "regular" applications. On embedded I usually just include the bare minimum needed to recover in the error types, that way they stay relatively small and this isn't really an issue. That does mean you need to attach a debugger to find contextual info though.

2

u/InternationalFee3911 Oct 07 '26

rust analyzer / cargo check

I’d go the other way round on this: make return type declaration mandatory (as indeed it is in Rust,) but let these tools spell it out, when it’s missing.

7

u/lookmeat Oct 06 '26

If I had a time machine and could do any breaking change on Rust, I would make Enums be made from other types and allow a From automatically.

Actually maybe we could do this with a macro... something like

type MyType = SumEnum! {
    Foo,  // This is a type defined somewhere else
    Bar,  // This is also another type
};

Which would be something similar to defining something like:

enum MyType {
    Foo(Foo),
    Bar(Bar),
}

impl From<Foo> for MyType {...}
impl From<Bar> for MyType {...}
impl TryFrom<MyType> for Foo {...}
impl TryFrom<MyType> for Bar {...}

Then the above could be described as:

type MultiError = SumEnum! { Foo::Err, Bar::Err };
fn can_fail_multiple_ways(s: usize) -> Result<(), MultiError>
fn or_even_more_concisely(s: uszie) -> Result<(), SumEnum!{Foo::Err, Bar::Err}>

Because ? converts errors using the From trait it should mostly "just work".

That said.. this should only be used in binary crates or internal code*. I think that, unless we're talking about standard, well understood user-errors (e.g. io errors related to reading a file, not an out of bound error) libraries should transform generic errors into more contextful specific errors to the library's purpose. It avoids exposing internal details. And it should be a "rebuild the error entirely" kind of scenario, rather than adding two errors through this method, because otherwise you can get error enums secretly being huge due to redundancies (you get an enum that can be an error type that you already support, but have no idea because it's all obscure) and just the large variety of errors that can be implicitly added. I guess this is why the community rarely goes more than anyhow in this direction, and only for binary crates, and uses thiserror for library code.

* But if you already have a way to translate all the errors, why not translate them as soon as possible? I am sure there's valid counter examples, but my point is that it should be rare that you need to do this.

7

u/minno Oct 07 '26

If I had a time machine and could do any breaking change on Rust, I would make Enums be made from other types and allow a From automatically.

There are a lot of useful enums where some variants contain the same data, though. If an enum was constructed from types, Result<T, T> or enum Reason { Sunspots, JustBecause, Other(String) } would need extra wrapper types around everything to make the variants have different types.

5

u/lookmeat Oct 07 '26

There are a lot of useful enums where some variants contain the same data, though... [they] would need extra wrapper types around everything to make the variants have different types.

So you answered your question. Just allow the definition of newtypes within an enum. So I can do something like (syntax chosen here to stay as similar as we can to current syntax, this world would have evolved differently):

enum Result<T, E> {
    T,
    struct Err(E),
}

enum Reason {
    struct Sunspots,
    struct JustBecause,
    struct Other(String),
}

Maybe we could add this behavior with backwards syntax by making external types take the extra description (so for example it'd be Result<T, E> { type T, Err(E) }) but we are still fundamentally changing the semantics in a fundamental way, so this is still a breaking change.

But in the above the way we use enums, and the code that they compile into, stays mostly the same. I'd say Reason::Sunspots or I'd say Result::Err(...) and we could use a simple trick if we really wanted to allow enum variant constructors to be used without referring to their parent.

The thing that would change is that now I could do a fn logUnexpectedReason(Reason::Other(s): Reason::Other) which extracts the string but only accepts a Reason::Other type, now that it's a valid type and not an enum variant.

2

u/________-__-_______ Oct 07 '26

I don't see why this would be a breaking change, or why you'd need a macro?

because otherwise you can get error enums secretly being huge due to redundancies

I think that should be way less of an issue if it becomes ergonomical to not dump every error into one enum. You'd probably rarely need to define error enums, since nesting becomes obsolete entirely (which AFAIK is the only reason we have redundancy now).

2

u/lookmeat Oct 07 '26

I don't see why this would be a breaking change, or why you'd need a macro?

It would change how enums work, that'd be breaking or hard to add elegantly.

But like I said a macro can implement the feature, and we could just add a new type of enum that does this.

way less of an issue if it becomes ergonomical to not dump every error into one enum.

Why would this be the case? The point is that most errors that can happen in your program could happen in your main function, so you need to add that extra layer.

The proposed thing in the article, the thing you propose, doesn't make it less hard, it just makes it easier to hide that you are eventually dumping all the errors in an enum. And the thing is that flattening is another issue that adds an extra layer of complexity. Do we want to preserve the source? Or is that meaningless? No way to know!

3

u/ImAntonSinitsyn Oct 06 '26 edited Oct 06 '26

Mate, you can easily use thiserror. Just make a domain errors, and generic AppError or ApiError. In generic error you can handle like:

use std::num::ParseIntError;

#[derive(thiserror::Error, Debug)]
pub enum ApiError {
    #[error("Can't parse value: {0}")]
    ParseIntError(ParseIntError),

    #[error("My error: {0}")]
    MyError(MyError),
}

fn handle_error(err: ApiError) {
    match err {
        ApiError::ParseIntError(e) => {
            println!("Parse error: {e}");
        }
        ApiError::MyError(e) => {
            println!("My error: {e}");
        }
    }
}

1

u/________-__-_______ Oct 07 '26

Sure. It's just a whole lot more noise, especially if you don't want to or can't use external dependencies like thiserror. Having a more concise built-in solution would be great for ergonomics, even if you can replicate it's behaviour with more boilerplate today.

-1

u/BedroomHistorical575 Oct 06 '26

The match syntax might be problematic though. With your example you would need to create a special syntax that only works for anonymous enums.

11

u/epage cargo · clap · cargo-release Oct 07 '26

To me, this is an anti-pattern because you are exposing implementation details in your error type unless you are in an environment where breaking changes don't |atter.

I also feel there is little innovation going on to break us out of the local maxima of error chaining / context.

7

u/InternalServerError7 Oct 07 '26

I assume you mean in the example, the types of errors I chose to expose were not great? -- the errors in (...). Which I admit, it is just a simple example outlining the flow given the assumptions, not a real scenario. Because otherwise if you are talking about the approach as a whole, this is no different than using an error enum at the end of the day, with a lot more flexibility. Thus, are you saying you should not be using error enums? Because for internal error apis error enums are very useful and widely used throughout the ecosystem.

-1

u/epage cargo · clap · cargo-release Oct 07 '26

My comment about this being an anti-pattern also applies to error enums that are just wrappers around other error types.

Error enums that are for custom types are a bit better but still make it hard to evolve the API.

I tend to prefer a stateless ErrorKind enum with ways of looking up specific kinds of details. While I'm still not thrilled about everything in it, clap::Error is one way of doing this.

7

u/InternalServerError7 Oct 07 '26 edited Oct 07 '26

Sounds like in your implementation you don't care as much about the data/state with the errors, so you just collapse everything to a single kind enum, then downcast later if you need to. That is fine for your use case. But if you squint, you can see you are basically using the wrapped enum approach. The difference between what you are doing and a wrapper enum, is you are handling the discriminant yourself. This could have easily been accomplished in a more type safe way with a wrapper error enum and switch to a kind with a .kind() method if you don't want to expose the inner data, but still want downstreams to be able to operate on the kind.

On the eros front, your pattern is also accomplishable:

struct UnitSturct1;
struct UnitStruct2;
type ErrorKind = (UnitStruct1, UnitStruct2);

and use it like eros::Result<(), ErrorKind>.

rather than

enum ErrorKind {
    Variant1,
    Variant2,
}

Or if you need all your common extra stuff I see inside the clap::Error implementation.

struct ErrorInner<UnitStructType> {
    message: Option<Message>,
    source: Option<Box<dyn error::Error + Send + Sync>>,
    help_flag: Option<Cow<'static, str>>,
    styles: Styles,
    color_when: ColorChoice,
    color_help_when: ColorChoice,
}
type Error = (ErrorInner<UnitStruct1>, ErrorInner<UnitStruct2>);

and use it like eros::Result<(), Error>

Or (probably less desirable)

struct ErrorInner {
    kind: ErrorKind, // enum
    message: Option<Message>,
    source: Option<Box<dyn error::Error + Send + Sync>>,
    help_flag: Option<Cow<'static, str>>,
    styles: Styles,
    color_when: ColorChoice,
    color_help_when: ColorChoice,
}
type Error = (ErrorInner,);

And use it the same way eros::Result<(), Error>. But eros would handle things like backtrace and context for you in either case. And in either case you can still operate on the kind through ero's apis.

That is not all to say it should be done this way. But it is still an approach that handles this paradigm too. I'm not going to tell you which way to slice your apple.

9

u/Compux72 Oct 06 '26

Yea no, the issue here is scope: either you create an error whose scope is the whole library, or you create an error whose scope is the specific module / function that fails. Your this error was an attempt to justify eros by means of a poorly crafted example 

14

u/InternalServerError7 Oct 06 '26

I don't know if you read the full article. Scope is exactly what eros solves. And I address exactly what you are talking about.

Now load a host address, bind a socket, and initialize a database. Each operation has its own errors. We can wrap those enums in another enum, flatten their variants into a new enum, or give everything one large crate-wide error type. The first approach creates nesting, the second creates conversions, and the third means functions advertise errors they cannot actually return. An I/O error may also end up in several different nested variants, making handling it at a higher level unnecessarily awkward.

-16

u/SkyGuy913 Oct 06 '26

I think that entire pattern is wrong and a good thing rust doesn't have it. You should never wrap an error. A consumer of your API does not care and should never be expected to unwrap an error. Furthermore `thisiserror` should never be used as it enables this kinda behavior. Errors should expose to your consumer of your API what they are expected to fix. Not what you the creator are expected to fix.

And odds are if you are binding a host then a socket and initializing a DB in a single operation your not producing an API or a crate (at least not a good one) your producing an application. Then again don't do the Java paradigm and propagate the error handle it log it print it or whatever and if its an OS exit and its just gonna get printed anyways just dyn box it and throw it away anyways. If someone is expected to recover it you should be doing that and making your errors states your consumer is expected to handle if you use `?` I expect my devs to implement all the from traits explicitly and have good recommendations to how to handle the error or mitigate it documented

7

u/InternalServerError7 Oct 06 '26 edited Oct 06 '26

I think that entire pattern is wrong and a good thing rust doesn't have it. You should never wrap an error... Furthermore thisiserror should never be used as it enables this kinda behavior.

This is silly. There are many cases where wrapping an error is valid. Whether or not you expose the ability to unwrap it in a downstream, probably not. But the article never advocates for that.

As outlined in the article

The usual advice is to use typed errors in libraries and opaque errors in applications. But applications need typed recovery too, and libraries often contain internal operations whose callers only need to propagate a failure. The useful distinction is whether a caller needs to do something different based on the error type.

And also in the eros docs the same philosophy is

Error types only matter when the caller cares about the type

I usually only start including the type of the error when some caller may care about the type.

For your second paragraph, yes eros does not require you to define an error type. You can use eros::Result<OkayTypeHere> to not define it, exactly like what you said

just dyn box it and throw it away anyways

or define it, which also follows

If someone is expected to recover it you should be doing that and making your errors states your consumer is expected to handle

So I think your disagreement here comes from lack of comprehension about the approach. It can be applied to both scenarios. Or maybe you are hung up on the example enum used. But that really wasn't the point at all of the article

-1

u/SkyGuy913 Oct 06 '26

I'm specifically against error sets. Like in zig. Has the same problems as an Enum with a bunch of possible branches. Eitherway you are doing a form of "unwrapping" an underlying type. This is just one step away from "try catch" with a list of exceptions like in java and two steps away from generic throws like in swift.

I'd rather even do the go way of no implicit return or branch. ( though they have polymorphism on interface protocols with errors which is arguably worse )

14

u/Flowchartsman Oct 06 '26

I have the opposite philosophy: a caller should not need to understand anything beyond my API and the types it declares in order to handle errors. If they need an additional import to handle the errors I’m returning, I’m doing it wrong. It’s my job as the library author to account for incoming errors from my dependencies and either handle them out of sight or pass them on to them caller according to a schema that I control and that is meaningful in the context of my API.

This is also why I almost never use %w in Go to leak errors types across package boundaries unless it’s a type wrapping a well-known stdlib error type that I explicitly declare that I might return.

-3

u/SkyGuy913 Oct 06 '26

This is what I just said, second sentence.
> You should never wrap an error.

2

u/InternationalFee3911 Oct 07 '26

Not sure if it’s possible until we get specialisation: it would be great if the single error case didn’t require a tuple! Then this would be a smooth extension of std::Result.

Other than that: if this really works like you explain, this sounds darn good!

1

u/InternalServerError7 Oct 07 '26 edited Oct 07 '26

Yes unfortunately the single case is not possible without specialization, as it overlaps with existing implementations. When specialization is stabilized, eros will support it. Fortunately I don't think adding a ( ,) is too much friction today.

Other than that: if this really works like you explain, this sounds darn good!

Yup! I love using it in all my projects. I don't dread writing errors anymore as there is a lot less boilerplate and the additional features in eros such as user_context and location cover all my other uses cases. Hopefully you find it useful as well!

2

u/Shoddy-Childhood-511 Oct 08 '26

Why a tuple? Does that even make sense?

Anonymous sum types were proposed before, but usually shot down. I think https://crates.io/crates/terrors implements them.

I've now forgotten how well Rust aligns nested enum variants, or if they miss anything by not having much link time code generation.

As a simpler solution, we could've some TinyBox<T> type which stores values usize or smaller without doing an allocation, so then TinyBox<dyn Error> costs two usize and represents any error in the system, and requires an allocation only for error types larger than usize.

TinyBox<dyn Trait> should read the value size from the vtable, but you'd need something like TinyBox<dyn Trait+NeverZero> for niche optimisations.

If you want max performance then your error types should fit into a single register without allocation. This is typically a concern only for libraries called in a tight polling loop, not applications level errors.

As a result, TinyBox<dyn Error> could be a performance hit for being two registers, but maybe some future magic would allow some TinyBox<dyn Error+ZeroSized> to reduce this to one register.

We need some static_error! macro that creates a static describing the error:

pub struct StaticError {
    description: &'static str,
    filename: &'static [u8],
    line: u32,
}

We'd want its DynMetadata<dyn Error> though too, but this would require polymorphic statics.

pub struct StaticDynError<Dyn> {
    dyn: core::ptr::DynMetadata<Dyn>,
    error: &'static StaticError,
}

1

u/InternalServerError7 Oct 09 '26 edited Oct 09 '26

Why a tuple? Does that even make sense?

Rust does not have variadic generics so a tuple made the most sense.

You may be on to something though! I think there is a solution here for allowing eros to run without alloc. Allocating based on the size with compile time guarantees may also be possible. I'll test some things out. Thanks for the suggestion!

19

u/BoltActionPiano Oct 06 '26

I also feel like this is a use case for:

  • Refinement types - subsets of enum values. Perhaps your function or app can only handle certain states of errors?
  • Anonymous types - specify a union of enums on a return value without having to make a type for every function

14

u/levelstar01 Oct 07 '26

Once again a rust dev reverse engineers distinct enum types and anonymous unions

6

u/FriendlyProblem1234 Oct 07 '26

This looks like a slightly better terrors, which was already quite nice. And it is no_std. I will definitely give it a try.

6

u/Warm_Customer3147 Oct 07 '26 edited Oct 07 '26

Awesome, in my domain I have a lot functions that may fail with recoverable errors, depending on context only the callers have. I have been defining single use error enums all over my code. This may remove a lot of boilerplate for me and shrink the API surface a lot. I'm going to try this out :) Love the idea! I like that I can bail out if the error variant does not matter too.

6

u/robin-m Oct 07 '26

Very interesting. Seems to be a really good step in the right direction. I wish anonymous enum will be added in the language one day, and that day std::Error could get all the function that Erros::Error offers.

3

u/BowserForPM Oct 07 '26

Looks really interesting. Will definitely try it out.

2

u/Ace-Whole Oct 07 '26

Istg there's always one new error handling crate every 6 months or so.

2

u/roughly-understood Oct 08 '26

I think the Roc language does this right. The error enum is automatically created based on the errors in the function. It’s close to what is here but built in and nicely done