Twitter期货上的Await.result是否有非投掷等效项?

时间:2018-10-18 01:48:26

标签: twitter future

com.twitter.util.Await.result(Awaitable)引发异常。

这是必要的,因为在异常的Future上调用Await.result会抛出Future包含的异常。

但是,如果我已经将一个完整的函数传递给Future.handle或Future.rescue,我知道我应该不会抛出任何非致命异常。

// Scala code
val s = Await.result(futureOfString.handle { case _ => "some default" })

但是,当从Java调用Await.result时,我要么将其放在try块中,要么在调用方法的throws子句中列出Exception,然后将检查到的Exception传播到调用堆栈中。

// Java code
// Add throws clause, and add it to every caller too
String someMethod(Future<String> future) throws Exception {
   return Await.result(future.handle(func(e -> "default")));
}

或者,

// Java code
// convert Exception to unchecked
String someMethod(Future<String> future) {
   try { 
      return Await.result(future).handle(func(e -> "default"));
   } catch(Exception e) {
      throw new RuntimeException(e);
   }
}

因此,我希望在Twitter util库中看到将已检查的异常转换为未检查的异常的内容,例如:

// Scala code
silentResult[T](Future[T] future) : T = try { 
   Await.result(future)
} catch {
  case e: Exception => throw new RuntimeException(e);
}

由于我没有看到假设的silentResult之类的东西,所以我猜有更好的方法吗?

(是的,我根本不应该等待,我应该只返回Future,但是在这种情况下,我已经建立了防止该情况的API。)

0 个答案:

没有答案
相关问题