0

我正在使用 Play Framework 2.1.5 和 ReactiveMongo 0.9 使用 ReactiveMongo Play 插件开发一个简单的 RESTful Web 服务。自从我最后一次使用 Play Framework 已经有很长时间了。我正在尝试使用以下方法插入文档:

def create = Action(parse.json) { request =>
  Async {
    val coll = db.collection[JSONCollection](...)
    val obj = Json.obj(
                "username" -> ...,
                ...
              )

    users.insert(obj).map { err => err match {
      case e if !e.ok => InternalServerError(Json.obj("result" -> 0, "error" -> e.message))
      case _ => Ok(Json.obj("result" -> 1))
    }}
  }
}

我预计一旦查询执行失败(例如由于索引中的重复值),我会毫无问题地处理它。但它的工作方式不同 - 如果失败,则抛出 a而不是用适当的值DatabaseException满足 the 。Promise[LastError]请问我错过了什么?

4

3 回答 3

2

当将来发生异常时,任何对 map 的调用都将被忽略,并且异常将沿着期货链传递。

可以使用recover和来显式处理 Futures 链中的异常recoverWith。您可以在 scala-lang 文档中的期货概述中了解更多信息:http: //docs.scala-lang.org/overviews/core/futures.html#exceptions

于 2013-11-22T14:08:44.477 回答
0

试试这个代码 -

def insert(coll: BSONCollection, doc: BSONDocument): Future[Unit] = {

val p = Promise[Unit]
val f = coll.insert(doc)
f onComplete {
  case Failure(e) => p failure (e)
  case Success(lastError) => {
    p success ({})
  }
}
p.future
}
于 2015-02-20T11:46:54.927 回答
0

我希望这可以简化您的需求...

def create = Action (parse.json) { request => 
   Async {
     val coll = db.collection[JSONCollection](...)
     val obj = Json.obj ("username" -> ...)
     users.insert(obj).map {
        case ins if ins.ok => OK (...)
        case ins => InternalServerError (...)
     } recover {
        case dex: DatabaseException => 
          log.error(..)
          InternalServerEror(...)
        case e: Throwable =>
          log.error (..)
          InternalServerError (...)
     }
   }
 }      
于 2016-04-26T07:23:07.643 回答