斯卡拉。如何在成功时从 Future 中获取值,在失败时抛出异常?
Scala. How can I take a value from Future on success, on failure throw exception?
我有一个代码(getServiceBySid
函数returnsFuture[ServiceCategory]
):
var service: ServiceCategory =
Await.result((for {
optService <- getServiceBySid(serviceSid)
} yield {
optService
}) recover {
case e: Throwable =>
throw e
}, Duration(10, TimeUnit.SECONDS))
而且我一直认为这段代码不是真正的 Scala 风格。实际上它做了类似
val serviceCategory: ServiceCategory =
getServiceCategoryBySid(serviceCategorySid) onComplete {
case Success(value) => value
case Failure(e) => throw e
}
但是onComplete returns Unit
,所以它不起作用。我该如何重构代码?
你可以简单地写
Await.result(getServiceBySid(serviceSid), Duration(10, TimeUnit.SECONDS))
因为如果你 Await.result
在 Future
上它会 return 如果成功或抛出被失败捕获的异常的值 Future
.
我有一个代码(getServiceBySid
函数returnsFuture[ServiceCategory]
):
var service: ServiceCategory =
Await.result((for {
optService <- getServiceBySid(serviceSid)
} yield {
optService
}) recover {
case e: Throwable =>
throw e
}, Duration(10, TimeUnit.SECONDS))
而且我一直认为这段代码不是真正的 Scala 风格。实际上它做了类似
val serviceCategory: ServiceCategory =
getServiceCategoryBySid(serviceCategorySid) onComplete {
case Success(value) => value
case Failure(e) => throw e
}
但是onComplete returns Unit
,所以它不起作用。我该如何重构代码?
你可以简单地写
Await.result(getServiceBySid(serviceSid), Duration(10, TimeUnit.SECONDS))
因为如果你 Await.result
在 Future
上它会 return 如果成功或抛出被失败捕获的异常的值 Future
.