Reputation: 45
I have a Tag.scala file in my Play Framework app with TagKeys and TagValues defined. I want to throw a MappingException when the json is misformatted or the keys/values passed do not belong to TagKey and TagValue.
The json I'm expecting is
"tags": [{"key": "Key1", "value": "Value1"}, ....]
and it will get converted into a Option[Seq[Tag]]
I want to throw an error for misformatted json or for invalid keys/values, but the MappingException seems to be getting lost somewhere and the Serializer returns an empty Sequence.
Also, when I don't catch the NoSuchElementException and just do the conversion without any try catch, I get a org.json4s.package$MappingException: unknown error
case class Tag(tagKey: TagKey, tagValue: TagValue)
sealed abstract class TagKey
object TagKey {
case object Key1 extends TagKey
case object Key2 extends TagKey
}
sealed abstract class TagValue
object TagValue {
case object Value1 extends TagValue
case object Value2 extends TagValue
}
object TagSerializer extends CustomSerializer[Tag](_ =>
(
{
case JObject(List(("key", JString(k)), ("value", JString(v)))) =>
try Tag(TagKey(k), TagValue(v))
catch {
case ex: java.util.NoSuchElementException =>
throw new MappingException(s"Invalid key/value for tags. Error: $ex")
}
case unknownJson: Any => throw new MappingException("Invalid Json")
},
{ case x: Tag =>
JObject(List(("key", JString(x.tagKey)), ("value", JString(x.tagValue))))
}
)
)
I then add this TagSerializer to the formats in my custom body parser. The serialization deserialization works fine.
What am I doing wrong here? Why isn't the error showing up?
Upvotes: 1
Views: 64