So, the current implementation uses twitter's Future
along with throwing exceptions to signal invalid use-case along with for-comprehensions
, like so:
def someMethod(a: ...): Future[X] = {
// do something
// if something goes wrong throw exception
throw new Exception("Certificate not issued")
}
// in some other method, where exceptions break the loop and exit
def someOtherMethod(a: ...): Future[Y] = {
for {
x <- someMethod(...)
y <- yetAnotherMethod(...) // which throws another exception
} yield y
}
The general idea being, when something goes wrong, an exception gets thrown, which will cause exit from the for-comprehension
block.
I want to get away from throwing exceptions. One way to solve it is, returning Either[Error, X]
, and the other way ADT
using sealed trait
. So, instead of throwing an Exception
you can return Left(Error)
or an ADT
like case object NoCertificate extends CertificateResponse
.
Question is: Can I keep the existing for loops intact, if I replace the methods which currently has throw Exception
with Either
or ADT
?
For sake of completeness, here's how I would code my Either
and ADT
:
sealed trait Error
case object CertificateError extends Error
case object SomeOtherError extends Error
def someMethod(a: ...): Future[Either[Error, CertificateResponse]] = {
// returns Left(CertificateError) or Right(CertificateResponse)
}
OR
sealed trait CertificateResponse
case class Certificate(x509) extends CertificateResponse
case object NoCertificate extends CertificateResponse
def someMethod(a: ...): Future[CertificateResponse] = {
// returns NoCertificate or Certificate(X509)
}
will either of these alternative solution (to throwing exceptions and breaking referential transparency), work with for-comprehensions
? Will the negative response: Left()
or NoCertificate
automagically exit the for-comprehension
block? If not, how to make it, such that I can keep the for-comprehension
blocks as is? Something akin to cats EitherT's leftMap
?
Please Note: We cannot use cats
Monad Transformer like EitherT
(which has leftMap
which signals exit conditions), as that is not one of the libraries we use in our stack. Sorry!
Thanks!