Skip to content

Commit

Permalink
Add information about which required field was missing
Browse files Browse the repository at this point in the history
  • Loading branch information
gregor-i committed Nov 14, 2024
1 parent 945cee0 commit daebaa3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,23 @@ private[compiler] class ParseFromGenerator(
val r = (0 until (requiredFieldMap.size + 63) / 64)
.map(i => s"__requiredFields$i != 0L")
.mkString(" || ")
p.add(
s"""if (${r}) { throw new _root_.com.google.protobuf.InvalidProtocolBufferException("Message missing required fields.") } """
)
p.add(s"""if (${r}) {""")
.indent
.add("val __missingFields = Seq.newBuilder[_root_.scala.Predef.String]")
.print(requiredFieldMap.toSeq.sortBy(_._2)) {
case (p, (fieldDescriptor, fieldNumber)) =>
val bitmask = s"0x${"%x".format(1L << fieldNumber)}L"
val fieldVariable = s"__requiredFields${fieldNumber / 64}"
p.add(
s"""if (($fieldVariable & $bitmask) != 0L) __missingFields += "${fieldDescriptor.scalaName}""""
)
}
.add(
s"""val __message = s"Message missing required fields: $${__missingFields.result.mkString(", ")}"""",
s"""throw new _root_.com.google.protobuf.InvalidProtocolBufferException(__message)"""
)
.outdent
.add("}")
}
.add(s"$myFullScalaName(")
.indented(
Expand Down
2 changes: 1 addition & 1 deletion e2e/src/test/scala/NoBoxSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class NoBoxSpec extends AnyFlatSpec with Matchers {
"RequiredCar" should "fail validation if required field is missing" in {
intercept[InvalidProtocolBufferException] {
RequiredCar.parseFrom(Array.empty[Byte])
}.getMessage must be("Message missing required fields.")
}.getMessage must be("Message missing required fields: tyre1")
}

"RequiredCar" should "fail parsing from text if field is empty" in {
Expand Down

0 comments on commit daebaa3

Please sign in to comment.