Joram Visser
09/11/2020, 7:53 PMarrow-fx-coroutines
, that it will be a suspended function. Personally I really like to work with `Either`s, so most often I end up with a signature like suspend fun myMeaningfulLogic(): Either<DomainError, MeaningfulResult>
.
When using such functions, you need to fold the returned Either
so that you can create a response that is useful in an HTTP endpoint. And most often, just to be safe, because everything on the JVM can throw `Exception`s, you want to wrap your meaningful logic in an Either.catch
. Which means more folding to come to a usable value.
To simplify the Either.catch
with multiple `Either.fold`s, I created a generic function that can handle any suspended function that returns an Either
and return a desired type of value:
get("/some/http/endpoint") { // This is an example using Ktor.
handle(
logic = { myMeaningfulLogic() },
ifSuccess = { a -> handleSuccess(call, a) },
ifDomainError = { e -> handleDomainError(call, ::log, e) },
ifSystemFailure = { throwable -> handleSystemFailure(call, ::log, throwable) },
ifUnrecoverableState = ::log
)
}
This generic handler is not limited to endpoint implementations. It can handle any message or event in any framework (there is also a handleBlocking variant) and possibly there are more use cases to use it.
Feel free to check it out, see: https://github.com/sparetimedevs/pofpaf. Use it if you like it. Any feedback is welcome.raulraja
09/12/2020, 6:27 AMJoram Visser
09/12/2020, 6:47 AMraulraja
09/12/2020, 11:28 AMJoram Visser
09/12/2020, 9:38 PM