2015-10-28 95 views
0

我使用的是Scala/Slick 3.1(这是所有通过spray-slick-swagger typesafe activator),并有4个不同的查询运行,我想返回作为一个对象。我试图把所有的未来一起组合成一个未来。理解和选项的斯卡拉

它的工作原理,但问题是,如果查询失败(即,我们搜索不存在的东西),则存在运行时异常。

我想我真的是,如果一个查询失败,失败了整个事情,并最终返回一个未来的[选项]

整个事情经过喷雾迷上了

所以查询的代码如下所示:

// .. snip .. FindById() 
     val a = db.run(q1.result) // Future[Seq[Tuple]]] 
     val b = db.run(q2.result) 
     val c = db.run(q3.result) 
     val d = db.run(q4.result) 

     // compose the futures together into one future 
     val res = for { 
    resA <- a 
    resB <- b 
    resC <- c 
    resD <- d 
    } yield { 
     PhoneMerged(resA.head._1, resA.head._2, resB.map(x => FeaturesSimple(x.featurename)).toList, resD.map(x => FeaturesvaluepairSimple(x.featuretype, x.featurevalue)).toList, 
      resC.map(x => IncludedaccessorySimple(x.accessoryvalue)).toList, createPhoneImage(resA.head._1.devicemcd)) 
    } 

它被称为与

onComplete((modules.phonesDAA ? FindById(id)).mapTo[Future[PhoneMerged]]) { 
      case Success(phoneOption) => { 
      println(phoneOption) 
      complete(phoneOption) 
      } 
      case Failure(ex) => { 
      println("uh oh") 
      complete("{}") 
      } 
     } 

最终我想要返回JSON序列化的PhoneMerged对象(如果我搜索一个有效的ID,它的作品)或“{}”空JSON ...

任何人有任何想法如何正确处理结果/处理错误?

回答

1

您可以使FindById函数返回Future[Option[PhoneMerged]],并使用Future combinator(如recover)处理内部的故障情况。
例如:

val a = db.run(q1.result) 
    // Future[Seq[Tuple]]] 
    val b = db.run(q2.result) 
    val c = db.run(q3.result) 
    val d = db.run(q4.result) 

    // compose the futures together into one future 
    val res = for { 
    resA <- a 
    resB <- b 
    resC <- c 
    resD <- d 
    } yield { 
     Some(PhoneMerged(resA.head._1, resA.head._2, resB.map(x => FeaturesSimple(x.featurename)).toList, resD.map(x => FeaturesvaluepairSimple(x.featuretype, x.featurevalue)).toList, 
     resC.map(x => IncludedaccessorySimple(x.accessoryvalue)).toList, createPhoneImage(resA.head._1.devicemcd))) 
    } recover {case e: YourExceptionType => None}