typelevel / mouse

A small companion to cats
MIT License
368 stars 66 forks source link

Add getOrRaiseF #323

Closed geirolz closed 2 years ago

geirolz commented 2 years ago

Hi, dealing with nested effects is always complex and sometimes verbose, I found helpful these two methods in my codebase and I'd like to propose them here.

getOrRaiseF and getOrRaiseMsgF given F[G[A]] where F is a MonadError and G a foldable like Option and Either we can either get the nested value or raise an error in F if the value is missing ( since either is right biased).

Example

val fga: Try[Option[Int]] = Success(None)
val result: Try[Int] = fga.getOrRaiseMsgF("BOOM!")// = Failure(RuntimeException("BOOM!")

What do you think? (There are alternatives already in place? )

benhutchison commented 2 years ago

Overall, I'm feeling 👍 about the PR.

In terms of code, the PR is good. My only doubt, which as a maintainer I must consider, is "is the user base for this feature larger than the original contributor?"

In this case, given we already provide extensive support for working with F[Either] and F[Option] I think there are likely mouse users who could use these operations.

Re the getOrRaiseMsgF variants: I think I added toTryMsg years ago, and it does align with my experience that often, an error value is simply a string; it's intended to be read by a human, not pattern matched on. I'm OK with adding them, to save the user from having to wrap up a String into a Throwable.