Reputation: 1918
I'm trying to parse a json with Play Json, using as
to parse single "fields". Like this:
val data = (json \ "dataField").as[String]
This throws a JsResultException if unable to parse the field or invalid. However, as I need to output the error in a "freindlier" way, I need to set a custom JsResultException message.
Is there a way of achieving this? I could do something like:
(json \ "dataField").asOpt[String].getOrElse(throw new Exception("Error parsing dataField field."))
and then matching Some(data: String)... None... but it seems too much code for each field I need to parse.
Upvotes: 1
Views: 142
Reputation: 14803
When you use validate
you get a list of errors.
json.validate[MyClass] match {
case JsSuccess(myClass, _) =>
// do something
case JsError(errors) =>
// do something with the errors
}
The errors are of type Seq[(JsPath, Seq[JsonValidationError])]
.
You can transform this to whatever you want.
Upvotes: 1