我有一个函数db.writeDocument()
,在另一个名为DB.scala
的类中调用另一个函数saveToDB()
。 writeDocument()
函数接收JSON消息并将其发送到future
并期望返回db.writeDocument(message)
。
因此,在下面的代码中,您可以看到.map
返回正在reactivemongo.core.actors.Exceptions$PrimaryUnavailableException$: MongoError['No primary node is available!']
的函数,以查看成功结果或失败。
在事情的成功方面,一切都很有效,但是当我杀死MongoDB服务器时,500 Internal Server Error
永远不会被捕获,我得到的是Execution exception
,其响应正文包含def saveToDB(message: JsValue): Future[JsValue] = {
db.writeDocument(message).map { result =>
val resultJson = Json.obj("transactionID" -> (message \ "transactionID").get, "campaignID" -> (message \ "campaignID").get,
"status" -> "OK", "message" -> ("Valid Request Received"))
resultJson
}.recover { case e: Exception => {
BadRequest("Please check your MongoDB server" + e.toString)
Json.toJson("status -> error")
}
}
def writeDocument(json: JsValue): Future[WriteResult] = {
val db = getDBConnection
val collection = db.collection[JSONCollection]("Messages")
val document = json.as[JsObject]
val future = collection.insert(document)
future.onComplete {
case Failure(e) => {
throw e
}
case Success(result) =>
}
future
}
}
< / p>
saveToDB()
为了对我的问题完全公正,我试图以下列方式使用val saveResponseFromDB = saveToDB(message)
Future.firstCompletedOf(Seq(saveResponseFromDB, timeoutFuture)).map {
case resultJson: JsObject => {
val status = ((resultJson \ "status").get)
Ok(resultJson)
} case _ => BadRequest(Json.obj("campaignID" -> campaignID,
"status" -> "error", "message" -> "Error reading from the Database. Is it Down?") )
}
:(我已尽力解释这一点,如果您需要更多解释,请告诉我。)
def getDBConnection: DefaultDB = {
val driver = new MongoDriver
val connection = driver.connection(List(hostName))
val db = connection(dbName)
db
}
编辑1:
{{1}}