diff --git a/src/main/scala/scalapb/json4s/JsonFormat.scala b/src/main/scala/scalapb/json4s/JsonFormat.scala index 0c2b44c..f117344 100644 --- a/src/main/scala/scalapb/json4s/JsonFormat.scala +++ b/src/main/scala/scalapb/json4s/JsonFormat.scala @@ -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}") } } } @@ -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, diff --git a/src/test/scala/scalapb/json4s/JsonFormatSpec.scala b/src/test/scala/scalapb/json4s/JsonFormatSpec.scala index e030fb1..8ee7a32 100644 --- a/src/test/scala/scalapb/json4s/JsonFormatSpec.scala +++ b/src/test/scala/scalapb/json4s/JsonFormatSpec.scala @@ -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))