I have always used recover
to transform exceptions in failed futures similar to
def selectFromDatabase(id: Long): Future[Entity] = ???
val entity = selectFromDatabase(id) recover {
case e: DatabaseException =>
logger.error("Failed ...", e)
throw new BusinessException("Failed ...", e)
}
This code snippet transforms a DatabaseException
into a BusinessException
. However, from a comment in the question: Scala recover or recoverWith
... generally speaking the point of "recover" and "recoverWith" is not to simply transform your exceptions from one type to another, but to recover from the failure by performing the task in a different way so that you no longer have a failure.
So apparently I am not supposed to use recover
to transform exceptions. What is the correct way to transform Future
exceptions / failed Future
?
recover
(or slightly betterrecoverWith { .... Future.failed(new BusinessException
to avoid thethrow
) is fine. – Wed