我一直在处理我对Is there a standard Scala function for running a block with a timeout?的回答,并且如果在Future中引发异常,则会遇到问题。如何获取Scala Future中抛出的异常?
def runWithTimeout[T](timeoutMs: Long)(f: => T) : Option[T] = {
awaitAll(timeoutMs, future(f)).head.asInstanceOf[Option[T]]
}
这样
runWithTimeout(50) { "result" } should equal (Some("result"))
runWithTimeout(50) { Thread.sleep(100); "result" } should equal (None)
但是,如果我可以把我的块中的例外,但不得泄漏,但吞噬 - 这样下失败,“..no抛出异常”
intercept[Exception] {
runWithTimeout(50) { throw new Exception("deliberate") }
}.getMessage should equal("deliberate")
SYSERR具有与消息
<function0>: caught java.lang.Exception: deliberate
栈跟踪
但我无法找到打印的Scala运行时的哪个位置。
除了将f封装在另一个捕获异常的块中并在抛出异常时传播它们,有没有什么办法可以说服awaitAll和/或Future抛出?
它可能是打印,因为它被认为是传递给线程的[UncaughtExceptionHandler的] (http://download.oracle.com/javase/6/docs/api/java/lang/Thread.UncaughtExceptionHandler.html)。你可以设置你自己的处理程序,但是这仍然不允许你在另一个线程中抛出异常。 – 2011-06-03 16:36:12
看看Fingales期货(https://github.com/twitter/finagle),搜索“Timeout”和Akka http://akka.io/docs/akka/1.1.2/scala/futures.html – oluies 2011-06-03 17:48:07