相关疑难解决方法(0)

如何掌握Scala Future中抛出的异常?

我一直在努力回答是否有一个标准的Scala函数用于运行超时的块?,如果在Future中抛出异常,则会遇到问题.

  def runWithTimeout[T](timeoutMs: Long)(f: => T) : Option[T] = {
    awaitAll(timeoutMs, future(f)).head.asInstanceOf[Option[T]]
  }
Run Code Online (Sandbox Code Playgroud)

以便

runWithTimeout(50) { "result" } should equal (Some("result"))
runWithTimeout(50) { Thread.sleep(100); "result" } should equal (None)
Run Code Online (Sandbox Code Playgroud)

但是如果我在我的块中抛出一个异常它不会泄漏,但是被吞下 - 所以下面的代码失败了"..没有抛出异常"

intercept[Exception] {
    runWithTimeout(50) { throw new Exception("deliberate") }
}.getMessage should equal("deliberate")
Run Code Online (Sandbox Code Playgroud)

Syserr有一条带有消息的堆栈跟踪

<function0>: caught java.lang.Exception: deliberate
Run Code Online (Sandbox Code Playgroud)

但我无法找到Scala运行时中打印的位置.

除了在另一个块中包装f以捕获异常并在抛出时传播它们,有没有办法说服awaitAll和/或Future抛出?

concurrency scala exception-handling actor

15
推荐指数
2
解决办法
1万
查看次数

标签 统计

actor ×1

concurrency ×1

exception-handling ×1

scala ×1