Is there an ergonomic ? that works with Result<Result<T, E1>, E2>

If I have type T1: Into<E1>, and type T2: Into<E2>, I can't seem get something like this to compile:

fn func() -> Result<Result<T, E1>, E2> {
  function1()?;
  function2()?;
  Ok((T::new()))
}

where fn function1() -> Result<(), T1>, and fn function2() -> Result<(), T2>.

Maybe I am asking too much from the ? operator.

Is the only way to make this work to match on all calls that could return an error, and return the properly formed Ok(Err(E1)) or Err(E2)?

Why do you want to return a nested Result to begin with?

Ask yourself that question, and you might find the answer to the ergonomic problem you are facing :slight_smile: .

4 Likes

Ok, I think I found a workaround that works my current case.

Instead of returning Result<Result<T, E1>, E2>, I can define:

enum E {
  Error1(E1),
  Error2(E2)
}

with appropriate implementations T1: Into<E>, and T2: Into<E>, so that the function returns Result<T, E>.

Still would be nice to get ? to work for the nested Result.

2 Likes

A nested result does not make sense in most cases, since it's meaning would be, that the return type of a fallible operation is fallible. It may have niche use cases, but I cannot come up with any from the top of my head.
If you need to explicitly forward the source error types, your custom error type that can be created from the other two error types is the way to go.
If you don't really need that detailed information about the underlying error sources, you can look into crates like anyhow.

3 Likes

I have used nested results where outer error is “critical” and inner error needs to be processed further. In my case I used it for forms: inner error indicated that I need to display error message below some form input, and it prevented form from being actually submitted, but it did not prevent checking other inputs for errors, outer error were things like internal server error which stopped processing user request entirely and caused server to return a error page.

I remember somebody mentioned a crate with this kind of error logic (critical/non-critical errors) on this forum which used enum with three elements, but I have not saved its name and decided that I am better with nested results than with searching for it longer than for a few minutes.