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 2b87551
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
25 changes: 18 additions & 7 deletions src/main/scala/scalapb/json4s/JsonFormat.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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,
Expand All @@ -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}
Expand Down Expand Up @@ -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))
}

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, 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 2b87551

Please sign in to comment.