Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: add getErr() function to UnwrapException #9

Closed
mbucc opened this issue Jan 12, 2020 · 3 comments
Closed

Proposal: add getErr() function to UnwrapException #9

mbucc opened this issue Jan 12, 2020 · 3 comments

Comments

@mbucc
Copy link

mbucc commented Jan 12, 2020

When creating a domain entity with more than five fields (so zip is not available), the best pattern I've found goes like this:

data class T(val a: A, val b) {
  companion object {
    fun create(x1 : String?, x2: String?) : Result<T, DomainMessage> =
      try {
        Ok(T(
          A.create(x1).unwrap(), 
          B.create(x2).unwrap()));
      } catch (e:Exception) {
        Err(ParseError("error: ${e.message}");
      }
}   

What I'd like to be able to do is return the original DomainMessage from the catch block:

      } catch (e: UnwrapException) {
        e.getErr()
      }

Does this seem reasonable to you?

---- Edit: in proposed catch block, change Exception to UnwrapException

@michaelbull
Copy link
Owner

michaelbull commented Jan 12, 2020

I'm not a fan of throwing exceptions just to catch them to get some information out. I think a better approach is to instead have something along these lines:

fun exampleA(): Result<Int, String> = TODO()
fun exampleB(): Result<Int, String> = TODO()

data class Example(
    val a: Int,
    val b: Int
)

fun runExample(): Result<Example, String> {
    val a = exampleA().getOrElse { return Err(it) }
    val b = exampleB().getOrElse { return Err(it) }
    return Ok(Example(a, b))
}

The only downside is you end up recreating another Err in the failure state.

@mbucc
Copy link
Author

mbucc commented Jan 12, 2020

+1

BTW, thanks for this work. I found it after reading Scott Wlaschin's "Domain Modeling Made Functional" and have yet to run into something I cannot do. In fact, I was inspired to write a short blog post here: http://markbucciarelli.com/posts/2020-01-04_kotlin_functional_gold_mine.html)

@Munzey
Copy link
Contributor

Munzey commented May 9, 2020

just in case someone stumbles onto this issue, the functionality described is best captured by a monad comprehension.
I have opened a pr to add the functionality you are looking for:
#13

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants