Spyke

Syndicated from the fediverse. Read and engage on the original instance.

View original on lemmy.ml
rust·Rust Programmingbygomp

[newbie] Can I specify what subset of errors a function can return?

I have two functions that are similar but can fail with different errors:

#[derive(Debug, thiserror::Error)]
enum MyError {
  #[error("error a")]
  MyErrorA,
  #[error("error b")]
  MyErrorB,
  #[error("bad value ({0})")]
  MyErrorCommon(String),
}

fn functionA() -> Result<String, MyError> {
  // can fail with MyErrorA MyErrorCommon
  todo!()
}

fn functionB() -> Result<String, MyError> {
  // can fail with MyErrorB MyErrorCommon
  todo!()
}

Is there an elegant (*) way I can express this?

If I split the error type into two separate types, is there a way to reuse the definition of MyErrorCommon?


(*) by "elegant" I mean something that improves the code - I'm sure one could define a few macros and solve that way, but I don't want to go there

edit: grammar (rust grammar)

View original on lemmy.ml
9

3 replies

gompreply
lemmy.ml

Different functions whose possible failure reasons have a non-empty intersection, but don't coincide completely (IDK if this clarifies? I think the example code in the OP is clearer)

1

Yeah, I got that.

I'm asking what would be the benefit of not using a single error enum for all failure reasons?

1

You reached the end

[newbie] Can I specify what subset of errors a function can return? | Spyke