Exception handling in play framework parsing JSON

(Julian Wilson) #1


This is more of a design question since I’m new to Scala and play.

I have an endpoint on my API which in turn calls other 3rd party services (in different private methods) using play-ws. These services return JSON and I have to convert them into some case classes to do some manipulation before I send the final result back to the client. So the flow is like client -> endpoint -> multiple methods doing 3rd party calls -> endpoint -> client

I notice that the JSON serdes library doesn’t throw exceptions, but instead just has JsSuccess and JsError. Occasionally the parsing fails in the methods doing the 3rd party calls and I get some JsErrors. I want to handle failed parsing properly. If any of the parsing fails, the client should definitely get an HTTP 400.

My question is what’s a decent way to do this? I was thinking doing something like Left and Right to give the value or the error if there is a problem. I also had another idea of making an exception just for this and then using .recover, but this seemed a little smelly.

What are some good patterns here?


(Rich Dougherty) #2

A typical example is shown in the docs:

def savePlace = Action(parse.json) { request =>
  val placeResult = request.body.validate[Place]
    errors => {
      BadRequest(Json.obj("status" ->"KO", "message" -> JsError.toJson(errors)))
    place => {
      Ok(Json.obj("status" ->"OK", "message" -> ("Place '"+place.name+"' saved.") ))

Note that BadRequest is a 400 response.