How can I see how many documents were written & handle errors correctly?

90 Views Asked by At

From the documentation I can see that I should be able to use WriteResult.ok, WriteResult.code and WriteResult.n in order to understand errors and the number of updated documents but this isn't working. Here is a sample of what I'm doing (using reactiveMongoDB/Play JSON Collection Plugin):

   def updateOne(collName: String, id: BSONObjectID, q: Option[String] = None) = Action.async(parse.json) { implicit request: Request[JsValue] =>

     val doc = request.body.as[JsObject]
     val idQueryJso = Json.obj("_id" -> id)
     val query = q match {
         case Some(_) => idQueryJso.deepMerge(Json.parse(q.get).as[JsObject])
         case None => idQueryJso
     }

     mongoRepo.update(collName)(query, doc, manyBool = false).map(result => writeResultStatus(result))
   }

   def writeResultStatus(writeResult: WriteResult): Result = {

     // NOT WORKING
     if(writeResult.ok) {
       if(writeResult.n > 0) Accepted else NotModified
     } else BadRequest

   }
1

There are 1 best solutions below

1
On

Can I give an alternative approach here? You said:

"in order to understand errors and the number of updated documents but this isn't working"

Why you don't use the logging functionality that Play provides? The general idea is that:

  1. You set the logging level (e.g., only warning and errors, or errors, etc.).
  2. You could use the log to output a message in any case, either something is ok, or it is not.
  3. Play saves the logs of your application while it is running.
  4. You the maintainer/developer could look into the logs to check if there is any errors.

This approach open a great possibility in the future: you could save the logs into a third-party service and put monitoring functionalities on the top of it.

Now if we look at the documentation here, you see about different log levels, and how to use the logger.