[英]Scala: compose results of futures with exception handling
我是Scala的Future的新手,我还没有找到解决问题的方法。 我正在尝试实现以下目标(总体描述:尝试获取酒店列表的来宾列表,分别查询每个酒店):
这是我的代码。 HotelReservation
代表我将调用的外部API。
import com.typesafe.scalalogging.slf4j.Logging
import scala.concurrent._, ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
case class Guest(name: String, country: String)
trait HotelReservation extends Logging {
def getGuests(id: Int): Future[List[Guest]] = Future {
logger.debug(s"getting guests for id $id")
id match {
case 1 => List(new Guest("John", "canada"))
case 2 => List(new Guest("Harry", "uk"), new Guest("Peter", "canada"))
case 3 => {
Thread.sleep(4000)
List(new Guest("Harry", "austriala"))
}
case _ => throw new IllegalArgumentException("unknown hotel id")
}
}
}
object HotelReservationImpl extends HotelReservation
HotelSystem
拨打电话。
import com.typesafe.scalalogging.slf4j.Logging
import scala.util.control.NonFatal
import scala.util.{Failure, Success}
import scala.concurrent._, duration._, ExecutionContext.Implicits.global
class HotelSystem(hres: HotelReservation) {
def pollGuests(hotelIds: List[Int]): Future[List[Guest]] = {
Future.sequence(
hotelIds.map { id => future {
try {
Await.result(hres.getGuests(id), 3 seconds)
} catch {
case _: Exception =>
Console.println(s"failed for id $id")
List.empty[Guest]
}
}
}
).map(_.fold(List())(_ ++ _)) /*recover { case NonFatal(e) =>
Console.println(s"failed:", e)
List.empty[Guest]
}*/
}
}
和测试。
object HotelSystemTest extends App {
Console.println("*** hotel test start ***")
val hres = HotelReservationImpl
val hotel = new HotelSystem(hres)
val result = hotel.pollGuests(List(1, 2, 3, 6))
result onSuccess {
case r => Console.println(s"success: $r")
}
val timeout = 5000
Console.println(s"waiting for $timeout ms")
Thread.sleep(timeout)
Console.println("*** test end ***")
}
1和2正在工作。 3也是如此,但我想我在SO的某个地方读到,尝试抓住对未来的呼唤不是一个好主意,最好使用recovery。 但是,在这种情况下,如果我使用恢复,则如果有单个失败,则整个调用都会失败并返回一个空列表。 关于如何改善这一点的任何想法?
实际上,您可以做两件不同的事情:忽略尝试,不要对期货使用Await。
这是实现pollGuests
的更好方法:
Future.sequence(
hotelIds.map { hotelId =>
hres.getGuests(hotelId).recover {
case e: Exception => List.empty[Guest]
}
}
).map(_.flatten)
这里的第一点是,由于getGuests()
已经为您提供了Future,因此您不必在pollGuests()
使用Futures。 您只需使用recover()
创建一个新的Future,以便在返回Future时可能的故障已得到处理。
第二点是您不应该使用Await。 它使您的代码处于阻塞状态,直到Future准备就绪为止,例如可能冻结整个UI线程。 我假设您正在使用Await来使用try-catch,但是由于使用了restore recover()
您不再需要它了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.