加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Scala Future中抛出异常?

发布时间:2020-12-16 09:22:25 所属栏目:安全 来源:网络整理
导读:我一直在处理我对 Is there a standard Scala function for running a block with a timeout?的答案,如果未来抛出异常,就会遇到问题. def runWithTimeout[T](timeoutMs: Long)(f: = T) : Option[T] = { awaitAll(timeoutMs,future(f)).head.asInstanceOf[Opt
我一直在处理我对 Is there a standard Scala function for running a block with a timeout?的答案,如果未来抛出异常,就会遇到问题.

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,如果抛出异常并传播它们,是否有任何方式来劝说等待和/或将来抛出?

解决方法

简答:否

在线程上下文中,异常不会执行您想要的操作,因为您想了解调用者中的异常,并且将来的线程中会发生异常.

相反,如果你想知道异常是什么,你应该返回一个[Exception,What YouWant] – 当然,你必须在将来捕获这个异常并打包它.

scala> scala.actors.Futures.future{
  try { Right("fail".toInt) } catch { case e: Exception => Left(e) }
}
res0: scala.actors.Future[Product with Serializable with Either[Exception,Int]] = <function0>

scala> res0()   // Apply the future
res1: Product with Serializable with Either[Exception,Int] =
      Left(java.lang.NumberFormatException: For input string: "fail")

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读