How to improve the error message readability returned from JsError.toFlatJson or JsError.toJson in Play framework 2.x? How to improve the error message readability returned from JsError.toFlatJson or JsError.toJson in Play framework 2.x? json json

How to improve the error message readability returned from JsError.toFlatJson or JsError.toJson in Play framework 2.x?


Part of your problem can be solved by defining custom errors messages in your class' Reads combinator with orElse:

case Point(x: Int, y: Int)object Point {    implicit val pointReads: Reads[Point] = (        (__ \ "x").read[Int].orElse(Reads(_ => JsError("Could not parse given x value.")))        (__ \ "y").read[Int].orElse(Reads(_ => JsError("Could not parse given y value.")))    )(Point.apply _)}

Given some invalid JSON for this class you'll now get custom error messages for validation problems:

scala> val incorrectJson = Json.parse("""{"y": 1}""")incorrectJson: play.api.libs.json.JsValue = {"y":1}scala> val validationResult = incorrectJson.validate[Point]validationResult: play.api.libs.json.JsResult[playground.Point] = JsError(List((/x,List(ValidationError(List(Could not read the point's x value.),WrappedArray())))))scala> validationResult.fold(error => { println(JsError.toJson(error)) }, a => { a }){"obj.x":[{"msg":["Could not read the point's x value."],"args":[]}]}

In order to change the obj.x identifier you'll have to post-process the returned JsValue yourself because it's derived from the implementation of JsPath.