Skip to content

Commit 3c49e78

Browse files
Update JsonFormatException with field name and exception
1 parent 3b5428d commit 3c49e78

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

src/main/scala/scalapb/json4s/JsonFormat.scala

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,7 @@ class Parser private (config: Parser.ParserConfig) {
651651

652652
PMessage(valueMapBuilder.result())
653653
case _ =>
654-
throw new JsonFormatException(s"Expected an object, found ${value}")
654+
throw new JsonFormatException(s"Expected an object for ${cmp.scalaDescriptor.fullName}, found ${value}")
655655
}
656656
}
657657
}
@@ -723,11 +723,19 @@ class Parser private (config: Parser.ParserConfig) {
723723
res.fold[PValue](PEmpty)(PEnum.apply)
724724
}
725725
case ScalaType.Message(md) =>
726-
fromJsonToPMessage(
727-
containerCompanion.messageCompanionForFieldNumber(fd.number),
728-
value,
729-
false
730-
)
726+
try {
727+
fromJsonToPMessage(
728+
containerCompanion.messageCompanionForFieldNumber(fd.number),
729+
value,
730+
false
731+
)
732+
} catch {
733+
case ex: JsonFormatException =>
734+
throw new JsonFormatException(
735+
s"Failed parsing field ${fd.name}: ${ex.getMessage}",
736+
ex
737+
)
738+
}
731739
case st =>
732740
JsonFormat.parsePrimitive(
733741
fd.protoType,

src/test/scala/scalapb/json4s/JsonFormatSpec.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,17 @@ class JsonFormatSpec
456456
)
457457
}
458458

459+
"TestProto" should "fail to parse a field of type Message when it's not a json object" in {
460+
val jsonFormatException = intercept[JsonFormatException] {
461+
new Parser().fromJsonString[MyTest](
462+
"""{"optMessage": 39}"""
463+
)
464+
}
465+
jsonFormatException.getMessage must be (
466+
"Failed parsing field opt_message: Expected an object for jsontest.MyTest, found JInt(39)"
467+
)
468+
}
469+
459470
"TestProto" should "parse original field names" in {
460471
new Parser().fromJsonString[MyTest]("""{"opt_enum":1}""") must be(
461472
MyTest(optEnum = Some(MyEnum.V1))

0 commit comments

Comments
 (0)