Json exception capture using play-json library

play-json Json.parse() method may raise a JsonMappingException . It can also throw JsonParseException . To catch these exceptions, one need to get to com.fasterxml.jackson ?

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

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

This question is for Scala.

+6
source share
1 answer

I agree that it would be nice to have a secure parse flavor on Json , but its main task is to encode and decode, not serialize and deserialize (if you look at its description of ScalaDoc at the top level, for example, you will see the following: "Helper functions for processing JsValues ​​", not" for processing JSON strings ").

In general, getting from String to JsValue should be closer to the borders of your program, and if you look at how the incoming JSON on Play is processed, you will see that there are safe options (for example, request.body.asJson ).

It would also be useful to play Play to eliminate Jackson exceptions to avoid revealing implementation details, but you definitely don't need to β€œget” to β€œJackson” in any sense to catch these exceptions - just wrap the parse call in 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.

+6
source

Source: https://habr.com/ru/post/972057/


All Articles