I am trialing the use of Kotlin's Arrow library Either
object to handle exceptions within a project.
My experience with it thus far has been OK, but I'm struggling to find a way to handle transactions with Either
- and specifically rollbacks. In Spring throwing a RuntimeException
is a sure way to cause a transaction to rollback. However, by using Either
no exception is thrown and thus no rollback is triggered.
You can view this as a multifaceted question:
- Is
Either
appropriate for trueException
handling? Not alternative control flow, I mean true error situations where the flow of the program needs to stop. - If so, how do you achieve rollbacks with them?
- If the answer to question 2. is by using the
transactionManager
programatically - could you avoid that? - I'll squeeze this one in, how do you avoid nesting
Either
s?
Some of your questions don't have straight forward answers but I'll do my best :D
Spring uses exceptions to model trigger rollbacks, so in that case you need to abide by Spring's mechanisms.
If you prefer to use an
Either
API, you can probably wrap the exception based API of Spring with anEither<RuntimeException, A>
orEither<E, A>
one.So to answer your question,
Either
is appropriate for exception handling. However, typically you'll only catch the exceptions you're interessted and model them with your own error domain. Unexpected exceptions, or exceptions you cannot resolve are often allowed to bubble trough.Pseudo code example of wrapping
transaction: () -> A
withtransactionEither: () -> Either<E, A>
.And now you should be able to use
Either<E, A>
while keeping the exception based model of Spring intact.I answered question 2 while already avoiding it. Alternatively, by using the
transactionManager
programatically you could avoid having to throw that exception and recovering the value.Either#flatMap
oreither { }
to chain depenent values(Either<E, A>)
+(A) -> Either<E, B>
Either#zip
to combine independent values.Either<E, A>
+Either<E, B>
+(A, B) -> C
.