Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching Json exceptions with play-json library

play-json's Json.parse() method may throw a JsonMappingException. It may also throw a JsonParseException. In order to catch these exceptions, does one have to reach into com.fasterxml.jackson?

I understand from the documentation that play-json is built on top of Jerkson which is a wrapper around Jackson.

It seems much saner to catch an exception thrown by the play library rather than by a package that it uses which feels like reaching down through the abstraction. Is there a better way? Should the play-json library wrap these errors for better abstraction?

This question is for Scala.

like image 354
user650654 Avatar asked Jul 11 '14 00:07

user650654


1 Answers

I agree that it would probably be nice to have a safe flavor of parse on Json, but its primary focus is encoding and decoding, not serialization and deserialization (if you look at its top-level ScalaDoc description, for example, you'll see the following: "Helper functions to handle JsValues", not "to handle JSON strings").

In general getting from a String to a JsValue should happen closer to the boundaries of your program, and if you look at how incoming JSON is handled in Play, you'll see that there are safe options (e.g. request.body.asJson).

It would also probably be handy for Play to wrap the Jackson exceptions to avoid exposing implementation details, but you definitely don't need to "reach into" Jackson in any sense to catch these exceptions—just wrap the call to parse in a Try:

import play.api.libs.json._
import scala.util.Try

val parsed: Try[JsValue] = Try(Json.parse("{ broken"))

Or:

val decoded: Option[Map[String, Int]] = Try(
  Json.parse("""{ "foo": 1 }""")
).toOption.flatMap(_.asOpt[Map[String, Int]])

And so on.

like image 163
Travis Brown Avatar answered Sep 27 '22 23:09

Travis Brown