异常泄漏问题



我对异常泄漏有疑问。

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")可能会泄漏异常。

首先,我没有看到任何异常泄漏的情况,因为如果列表为空,它将因自定义异常而异常终止。您可以遵循的方法之一是使用 as 要么 将异常包装在 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
}

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

it might leak the exception without wrapping it的答案是处理异常而不是抛出它。你应该失败未来:

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

最新更新