From 2b875517f7595eee4a95fc5a2cc7c1198247590a Mon Sep 17 00:00:00 2001 From: github-vincent-baret Date: Wed, 19 Jul 2023 15:07:21 +0200 Subject: [PATCH] Update JsonFormatException with field name and exception --- .../scala/scalapb/json4s/JsonFormat.scala | 25 +++++++++++++------ .../scala/scalapb/json4s/JsonFormatSpec.scala | 11 ++++++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/main/scala/scalapb/json4s/JsonFormat.scala b/src/main/scala/scalapb/json4s/JsonFormat.scala index 0c2b44c..af22bd2 100644 --- a/src/main/scala/scalapb/json4s/JsonFormat.scala +++ b/src/main/scala/scalapb/json4s/JsonFormat.scala @@ -423,6 +423,7 @@ class Printer private (config: Printer.PrinterConfig) { ) private def unsignedInt(n: Int): Long = n & 0x00000000ffffffffL + private def unsignedLong(n: Long): BigInt = if (n < 0) BigInt(n & 0x7fffffffffffffffL).setBit(63) else BigInt(n) @@ -723,11 +724,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, @@ -740,6 +749,7 @@ class Parser private (config: Parser.ParserConfig) { } object JsonFormat { + import com.google.protobuf.wrappers // type GenericCompanion = GeneratedMessageCompanion[T] forSome { type T <: GeneratedMessage} @@ -875,8 +885,9 @@ object JsonFormat { def fromJsonEither[A <: GeneratedMessage: GeneratedMessageCompanion]( value: JValue - ): Either[MappingException, A] = try { Right(parser.fromJson(value)) } - catch { + ): Either[MappingException, A] = try { + Right(parser.fromJson(value)) + } catch { case e: JsonFormatException => Left(new MappingException("fail", e)) } diff --git a/src/test/scala/scalapb/json4s/JsonFormatSpec.scala b/src/test/scala/scalapb/json4s/JsonFormatSpec.scala index e030fb1..5d6cdea 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, found JInt(39)" + ) + } + "TestProto" should "parse original field names" in { new Parser().fromJsonString[MyTest]("""{"opt_enum":1}""") must be( MyTest(optEnum = Some(MyEnum.V1))