我一直习惯于recover
在失败的 future 中转换异常,类似于
def selectFromDatabase(id: Long): Future[Entity] = ???
val entity = selectFromDatabase(id) recover {
case e: DatabaseException =>
logger.error("Failed ...", e)
throw new BusinessException("Failed ...", e)
}
Run Code Online (Sandbox Code Playgroud)
此代码片段将 a 转换DatabaseException
为BusinessException
. 但是,从问题中的评论来看:Scala恢复或recoverWith
...一般来说,“recover”和“recoverWith”的要点不是简单地将异常从一种类型转换为另一种类型,而是通过以不同的方式执行任务来从故障中恢复,以便不再出现故障。
所以显然我不应该使用recover
来转换异常。Future
转换异常/失败的正确方法是什么Future
?