Map the Exception of a failed Future

前端 未结 2 1295
感动是毒
感动是毒 2020-12-28 12:58

What\'s the cleanest way to map the Exception of a failed Future in scala?

Say I have:

import scala.concurrent         


        
相关标签:
2条回答
  • 2020-12-28 13:24

    There is also:

    f recover { case cause => throw new Exception("Something went wrong", cause) }
    

    Since Scala 2.12 you can do:

    f transform {
      case s @ Success(_) => s
      case Failure(cause) => Failure(new Exception("Something went wrong", cause))
    }
    

    or

    f transform { _.transform(Success(_), cause => Failure(new Exception("Something went wrong", cause)))}
    
    0 讨论(0)
  • 2020-12-28 13:24

    You could try recoverWith as in:

    f recoverWith{
      case ex:Exception => Future.failed(new Exception("foo", ex))
    }
    
    0 讨论(0)
提交回复
热议问题