scalareactivemongoplay-reactivemongo

Handling update failure in Play 2.5 and ReactiveMongo


I have written simple rest API that will add music track data to mongodb.

I am able to write track successfully, however I would like to handle error case.

My code as below -

  def saveTrack = Action.async(parse.json) { 
     import model.Track.trackFormat
     implicit request =>
    request.body.validate[Track].map { data =>
      trackService.save(data).onComplete {
        case Success(value) => Ok(Json.obj("message" -> Messages("track.save.ack")))
        case Failure(e) => Ok(Json.obj("message" -> Messages("track.save.nack")))
    }
    }
    Future.successful(Ok(Json.obj("message" -> Messages("track.save.fin"))))
  }

Lets suppose there is some failure happen in trackService.save(data) then I want to return error code. I am wondering how to achieve that.

Thanks Pari


Solution

  • def saveTrack = Action.async(parse.json) { implicit request =>
        request
          .body
          .validate[Track]
          .map { data =>
            trackService.save(data).map { v =>
              Ok(Json.toJson(Json.obj("message" -> Messages("ack"))))
            }.recover {
              case _ =>
                Ok(Json.toJson(Json.obj("message" -> Messages("nack"))))
            }
          }.getOrElse {Future.successful(BadRequest(Json.obj("error" -> "bad json")))
        }
      }
    

    Use recover to handle errors and getOrElse in case the json body is not matching your model.