这与@luka-jacobowitz 给出的方法略有不同。通过他的方法,在“失败”之前发生的任何日志都将丢失。鉴于建议的类型:
type FutureErrorOr[A] = EitherT[Future, Error, A]
type MyStack[A] = WriterT[FutureErrorOr, Vector[String], A]
我们发现,如果我们使用WriterT 的run 方法扩展MyStack[A] 的值,我们会得到以下类型的值:
FutureErrorOr[(Vector[String], A)]
这与以下内容相同:
EitherT[Future, Error, (Vector[String], A)]
然后我们可以使用value 的EitherT 方法进一步扩展:
Future[Either[Error, (Vector[String], A)]]
在这里我们可以看到,检索包含结果日志的元组的唯一方法是程序是否“成功”(即右关联)。如果程序失败,则在程序运行时创建的任何以前的日志都无法访问。
如果我们采用原始示例并稍微修改它以在每一步之后记录一些内容,并且我们假设第二步返回一个 Left[Error] 类型的值:
val program = for {
age <- WriterT.liftF(getAge)
_ <- WriterT.tell(Vector("Got age!"))
dob <- WriterT.liftF(EitherT.fromEither(getDob(age))) // getDob returns Left[Error]
_ <- WriterT.tell(Vector("Got date of birth!"))
} yield {
dob
}
那么当我们评估结果时,我们只会返回包含错误的左侧 case,没有任何日志:
val expanded = program.run.value // Future(Success(Left(Error)))
val result = Await.result(expanded, Duration.apply(2, TimeUnit.SECONDS)) // Left(Error), no logs!!
为了获得运行我们的程序产生的值以及在程序失败之前生成的日志,我们可以像这样重新排序建议的 monad:
type MyWriter[A] = WriterT[Future, Vector[String], A]
type MyStack[A] = EitherT[MyWriter, Error, A]
现在,如果我们使用EitherT 的value 方法扩展MyStack[A],我们会得到以下类型的值:
WriterT[Future, Vector[String], Either[Error, A]]
我们可以使用WriterT 的run 方法进一步扩展它,为我们提供一个包含日志和结果值的元组:
Future[(Vector[String], Either[Error, A])]
使用这种方法,我们可以像这样重写程序:
val program = for {
age <- EitherT(WriterT.liftF(getAge.value))
_ <- EitherT.liftF(WriterT.put(())(Vector("Got age!")))
dob <- EitherT.fromEither(getDob(age))
_ <- EitherT.liftF(WriterT.put(())(Vector("Got date of birth!")))
} yield {
dob
}
并且当我们运行它时,即使在程序执行过程中出现故障,我们也可以访问结果日志:
val expanded = program.value.run // Future(Success((Vector("Got age!), Left(Error))))
val result = Await.result(expanded, Duration.apply(2, TimeUnit.SECONDS)) // (Vector("Got age!), Left(Error))
诚然,这个解决方案需要更多样板,但我们总是可以定义一些帮助器来帮助解决这个问题:
implicit class EitherTOps[A](eitherT: FutureErrorOr[A]) {
def lift: EitherT[MyWriter, Error, A] = {
EitherT[MyWriter, Error, A](WriterT.liftF[Future, Vector[String], ErrorOr[A]](eitherT.value))
}
}
implicit class EitherOps[A](either: ErrorOr[A]) {
def lift: EitherT[MyWriter, Error, A] = {
EitherT.fromEither[MyWriter](either)
}
}
def log(msg: String): EitherT[MyWriter, Error, Unit] = {
EitherT.liftF[MyWriter, Error, Unit](WriterT.put[Future, Vector[String], Unit](())(Vector(msg)))
}
val program = for {
age <- getAge.lift
_ <- log("Got age!")
dob <- getDob(age).lift
_ <- log("Got date of birth!")
} yield {
dob
}