问题描述
如果我有一个 Future[Either[String, Int]]
表示可能的错误消息 (String
) 或成功的计算 (Int
),将 Future
的潜在故障作为错误消息移到左侧很简单:
If I have a Future[Either[String, Int]]
that represents either a possible error message (String
) or a successful computation (Int
), it is simple to move the Future
's potential failure into the left side as an error message:
def handleFailure(fe: Future[Either[String,Int]]) =
f.recover({ case e: Exception => Left(s"failed because ${e.getMessage}"))
我希望 EitherT
存在类似的东西,但也许我只是找不到它的名字.它相对简单,但涉及拆箱和重新装箱,感觉很笨拙:
I would expect something similar to exist for EitherT
, but maybe I just can't find out what it is called. It is relatively simple, but involves unboxing and re-boxing the EitherT which feels kludgey:
def handleFailureT(fe: EitherT[Future, String, Int]) =
EitherT(handleFailure(et.value)) // See above for handleFailure definition
Cats 确实在 不久前添加了一个 MonadError
实例,但它专门用于直接恢复到Either 的right
,而不是替换Either 本身.
Cats did add a MonadError
instance a while ago, but it's specifically for recovering straight into the Either's right
, not for replacing the Either itself.
handleFailureT
是在 Cats 中实现的吗?如果是,它叫什么?
Is handleFailureT
implemented it Cats, and if so what is it called?
推荐答案
这并不明显,但我认为这就是 attempt
和 attemptT
的用途.例如:
It is not at all obvious, but I think this is what attempt
and attemptT
are for. For example:
val myTry: Try[Int] = Try(2)
val myFuture: Future[String] = Future.failed(new Exception())
val myTryET: EitherT[Try, Throwable, Int] = myTry.attemptT
val myFutureET: EitherT[Future, Throwable, String] = myFuture.attemptT
// alternatively
val myFutureET: EitherT[Future, Throwable, String] = EitherT(myFuture.attempt)
有一个 PR 将此添加到文档中:https://github.com/typelevel/cats/pull/3178 -- 但它目前没有出现在文档中.但是,您可以在这里看到它:https://github.com/typelevel/cats/blob/master/docs/src/main/tut/datatypes/eithert.md#from-applicativeerrorf-e-to-要么tf-ea
There was a PR to add this to the documentation: https://github.com/typelevel/cats/pull/3178 -- but it doesn't appear in the documentation currently. However, you can see it here: https://github.com/typelevel/cats/blob/master/docs/src/main/tut/datatypes/eithert.md#from-applicativeerrorf-e-to-eithertf-e-a
这篇关于将潜在的未来恢复到 Cats'EitherT's Left 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!