将尝试捕获替换为 Try in Scala

  • 本文关键字:Try in Scala 替换 scala
  • 更新时间 :
  • 英文 :

private def getDeviceDataByDeviceId(validId: String): Future[List[MonitoringData]] = {
try {
temperatureProcessorReadDAO.getTemperatureByDeviceId(validId).flatMap {
case Nil => throw TemperatureNotFoundException(TransportErrorCode.NotFound,
Error.DeviceErrorMessageForDataNotFound + validId)
case listOfMonitoringData => Future(listOfMonitoringData)
}
} catch {
case exception: Throwable => throw new Exception(exception.getMessage)
}

我必须更改这个特定的 scala 代码并将 try catch 替换为 Try 这是我所做的,但不正确

private def getDeviceDataByTimeInterval(validStartTime: String, validEndTime: String): Future[List[MonitoringData]] = {
Try(temperatureProcessorReadDAO.getTemperatureByTimeInterval(validStartTime, validEndTime)) match {
case Success(List()) => throw TemperatureNotFoundException(TransportErrorCode.NotFound,
Error.TimeIntervalErrorMessageForDataNotFound + validStartTime + validEndTime)
case Success(listOfMonitoringData) => listOfMonitoringData
case Failure(exception) => throw new Exception(exception.getMessage)
}
}

你能告诉我什么是正确的答案吗

我认为你根本不需要任何tryTry:看起来.getTemperatureByDeviceId返回一个Future,所以它不应该内联抛出任何东西,如果发生异常,只需返回失败的Future

如果它确实内联抛出,你最好的选择是修复它(在一个应该返回Future的函数中throw是一个非常糟糕的主意),或者,如果你由于某种原因不能,只需把它放在一个flatMap

Future
.successful(validId)
.flatMap(temperatureProcessorReadDAO.getTemperatureByDeviceId)
.map {
case Nil => throw TemperatureNotFoundException(...)
case result => result
}

作为旁注,永远不要抓住Throwable,改用case NotFatal(exception) => ...。无论如何,您的catch子句似乎毫无意义:您捕获所有内容,丢弃原始异常中的任何有用信息,例如类型或堆栈跟踪,然后只抛出仅包含原始消息的泛Exception。别这样。

最新更新