Search code examples
jsonscalaplayframeworkslick

How to handle a PSQL exception and return in my JSON action


I have a JSON action that returns a very simple JSON object that looks like:

case class InsertResponse(success: Boolean, message: String)

My action that returns JSON looks like:

def insertUser = Action.async(BodyParsers.parse.json) { request =>
  val userReq = request.body.validate[UserRequest]

  userReq.fold(
    errors => {
        Future(Ok(....))
    },
    userR => {

      val insertResultFut = 
        for {
           user <- .......
        } yield ....



        Ok(insertResponse.toJson)

    }
  )

}

So I want to catch certain exceptions that the insertResultFut call may throw, as it calls my slick database layer that inserts into the database.

I want to guard against a PSQLException that is thrown if the users email is a duplicate, how can I catch this error with futures?

If there is an exception, and it is a PSQLException for a duplicate key, I want to catch that and also set my InsertResponse success flag to false etc.

Thoughts?


Solution

  • You can use Future#recover for this case:

    insertResultFut.recover {
      case exe: PSQLException if exe.getMessage.contains("duplicate") => BadRequest(InsertResponse(false, "duplicate").toJson)
    }