Skip to content

Commit

Permalink
Update JsonFormatException with field name and exception
Browse files Browse the repository at this point in the history
  • Loading branch information
github-vincent-baret committed Jul 21, 2023
1 parent 3b5428d commit 1315cf6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/main/scala/scalapb/json4s/JsonFormat.scala
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ class Parser private (config: Parser.ParserConfig) {

PMessage(valueMapBuilder.result())
case _ =>
throw new JsonFormatException(s"Expected an object, found ${value}")
throw new JsonFormatException(s"Expected an object for ${cmp.scalaDescriptor.fullName}, found ${value}")
}
}
}
Expand Down Expand Up @@ -723,11 +723,19 @@ class Parser private (config: Parser.ParserConfig) {
res.fold[PValue](PEmpty)(PEnum.apply)
}
case ScalaType.Message(md) =>
fromJsonToPMessage(
containerCompanion.messageCompanionForFieldNumber(fd.number),
value,
false
)
try {
fromJsonToPMessage(
containerCompanion.messageCompanionForFieldNumber(fd.number),
value,
false
)
} catch {
case ex: JsonFormatException =>
throw new JsonFormatException(
s"Failed parsing field ${fd.name}: ${ex.getMessage}",
ex
)
}
case st =>
JsonFormat.parsePrimitive(
fd.protoType,
Expand Down
11 changes: 11 additions & 0 deletions src/test/scala/scalapb/json4s/JsonFormatSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,17 @@ class JsonFormatSpec
)
}

"TestProto" should "fail to parse when a message field is not a json object" in {
val jsonFormatException = intercept[JsonFormatException] {
new Parser().fromJsonString[MyTest](
"""{"optMessage": 39}"""
)
}
jsonFormatException.getMessage must be (
"Failed parsing field opt_message: Expected an object for jsontest.MyTest, found JInt(39)"
)
}

"TestProto" should "parse original field names" in {
new Parser().fromJsonString[MyTest]("""{"opt_enum":1}""") must be(
MyTest(optEnum = Some(MyEnum.V1))
Expand Down

0 comments on commit 1315cf6

Please sign in to comment.