将try catch替换为Scala中的Try

时间:2019-03-03 12:17:49

标签: 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)
    }
  }

您能告诉我什么是正确答案

1 个答案:

答案 0 :(得分:3)

我认为您根本不需要任何tryTry:看起来.getTemperatureByDeviceId返回了Future,所以它不应在行内抛出任何内容,如果发生异常,只需返回失败的Future

如果确实引发内联,则最好的选择是修复它(在应该返回throw的函数中Future确实是个坏主意),或者,如果可以, t由于某种原因,只需将其放在flatMap中:

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

请注意,切勿抓住Throwable,而应使用case NotFatal(exception) => ...。无论如何,您的catch子句似乎毫无意义:您捕获了所有内容,丢弃了所有有用的信息,例如原始异常的类型或堆栈跟踪,然后只抛出了原始的泛型Exception信息。不要那样做。