发生例外泄漏

时间:2018-05-04 05:37:44

标签: scala exception

我对异常泄漏有疑问。

 case class CustomException(message: String) extends RuntimeException(message)

   def listOfFut(list: List[Int]): Future[List[Int]] = {
          def handleFut(list: List[Int]): Future[List[Int]] = {
            if (list.isEmpty) throw CustomException("Test")
            else Future.successful(list)
          }
          for {
            myList <- Future.successful(list)
            result <- handleFut(myList)
          } yield result
        }

我做了同样的事情,比如上面的片段,但得到的反馈可能会泄漏异常而不包装它。 基本上,throw CustomException("Test")可能会泄漏异常。

2 个答案:

答案 0 :(得分:1)

首先,我没有看到任何异常泄漏的情况,就好像列表为空,它会因自定义异常而异常终止。您可以遵循的方法之一是使用Either将事件包装在Left中,将正确的输出包装在Right中。

但这将涉及更改方法签名

def listOfFut(list: List[Int]): Future[Either[Exception,List[Int]]] = {

  def handleFut(list: List[Int]): Future[Either[Exception,List[Int]]] = {
    if (list.isEmpty) Future.successful(Left(CustomException("Test")))
    else Future.successful(Right(list))
  }

  for {
    myList <- Future.successful(list)
    result <- handleFut(myList)
  } yield result
}

listOfFut(List()) onComplete {
  case Success(value) => println(s"Got the callback, meaning = $value")
    value match {
      case Right(output) =>
        println(s"Output is ${output}")
      case Left(ex) =>
        println(s"Exception is ${ex}")
    }
  case Failure(e) => e.printStackTrace
}

如果这回答了你的问题,请告诉我。

答案 1 :(得分:1)

def handleFut(list: List[Int]): Future[Either[Exception,List[Int]]] = { if (list.isEmpty) Future.failed(new CustomException("Test")) else Future.successful(Right(list)) } 的回答是处理异常而不是抛出异常。你应该失败的未来:

<ion-header>

  <ion-navbar>
    <ion-title>Settings</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding class="center">

  <div>
    <ion-row>
      <ion-col no-padding>
        <button ion-button text-capitalize padding block color="calm">
          Notifications
        </button>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col no-padding>
        <button ion-button text-capitalize block color="calm">
          Data
        </button>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col no-padding>
        <button ion-button text-capitalize block color="calm">
          Help
        </button>
      </ion-col>
    </ion-row>
  </div>
</ion-content>