Best way to catch some errors

I have an algorithm where there are broadly two types of errors:

  • A minor issue which I want to catch and deal with.
  • A major error which should bubble up and be returned.

I was just wondering if there is a nice / standard way of handling this situation?

I brief tried a Result<Result<A,B>,C>, where the outer C handled the serious error (which I returned with ?) and the inner Result had the minor errors, but to be honest while the code looked quite small I just keep confusing myself :slight_smile:

The way to handle this depends on whether the two kinds of error result from the same operation (such as both an EOF error and a ConnectionLosterror while reading from a socket) or different operations (like file-not-found with File::open() and EOF during the read).
With the former, you have no option but to match on the returned error type:

if let Err(err) = some_operation() {
  match err {
     MyError::Fatal(e) => return e; // Or return err;
     MyError::NonFatal(e) => { // Handle it here }

With the latter, it is easier - use an if let Err(...) on the non-fatal error and simply use ? with the fatal one.
The nested Result is really un-idiomatic and will only serve to confuse you and others in future (imagine seeing something like this: let a = operation()??; - I don't even know if it is valid syntax).

It's not wrong. If the failure cases are really different, and they're really supposed to be handled separately, then Result<Result<A, B>, C> might be OK.

function()?? is a valid syntax. Such error sandwich sometimes happens in Rust code, e.g. when you spawn a function on a thread, the join handle will give you its own result of spawning the thread wrapping another result of running the function.

But you could also simplify this by merging all your error types into a single enum, and leaving it up to the caller to match on cases they want to handle.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.